Esempio n. 1
0
def postfix_eval(input_str):
    """Evaluates a postfix expression"""

    """Input argument:  a string containing a postfix expression where tokens 
    are space separated.  Tokens are either operators + - * / ^ or numbers
    Returns the result of the expression evaluation. 
    Raises an PostfixFormatException if the input is not well-formed"""
    operators = ["<<", ">>", "**", "*", "/", "+", "-"]
    equation = input_str.split()
    stack = Stack(len(equation))
    for i in range(len(equation)):
        if is_num(equation[i]):
            stack.push(equation[i])
        elif equation[i] in operators:
            if stack.size() < 2:
                raise PostfixFormatException("Insufficient operands")
            first_num = stack.pop()
            second_num = stack.pop()
            if first_num == "0" and equation[i] == "/":
                raise ValueError
            try:
                total = eval(str(second_num) + str(equation[i]) + str(first_num))
            except TypeError:
                raise PostfixFormatException("Illegal bit shift operand")
            stack.push(str(total))
        else:
            raise PostfixFormatException("Invalid token")
    if stack.size() > 1:
        raise PostfixFormatException("Too many operands")
    if stack.size() == 0:
        return ""
    return float((stack.peek()))
Esempio n. 2
0
def infix_to_postfix(input_str):
    '''Converts an infix expression to an equivalent postfix expression
    Input argument:  a string containing an infix expression where tokens are
    space separated.  Tokens are either operators + - * / ** >> << parentheses ( ) or numbers
    Returns a String containing a postfix expression '''
    operators = Stack(30)
    input_list = input_str.split(" ")
    postfix = ""
    for i in range(len(input_list)):
        type = type_check(input_list[i])
        if type == 5:
            operators.push(input_list[i])
        elif type == 6:
            while not operators.is_empty() and operators.peek() != "(":
                postfix += operators.pop() + " "
            operators.pop()
        elif type == 0:
            postfix += input_list[i] + " "
        else:
            if operators.is_empty():
                operators.push(input_list[i])
            else:
                while not operators.is_empty() and (
                        type <= type_check(operators.peek()) < 5
                        and not type == type_check(operators.peek()) == 3):
                    postfix += operators.pop() + " "
                operators.push(input_list[i])
    while not operators.is_empty():
        postfix += operators.pop() + " "
    return postfix[:len(postfix) - 1]
Esempio n. 3
0
def postfix_eval(input_str):
    """Evaluates a postfix expression"""
    """Input argument:  a string containing a postfix expression where tokens 
    are space separated.  Tokens are either operators + - * / ** or numbers
    Returns the result of the expression evaluation. 
    Raises an PostfixFormatException if the input is not well-formed"""
    stack = Stack(30)
    input = input_str.split()
    for item in input:
        temp = item.replace('.', '', 1)
        temp = temp.replace('-', '', 1)
        if item.isalpha():
            raise PostfixFormatException("Invalid token")
        elif temp.isdigit():
            stack.push(item)
        else:
            if stack.num_items < 2:
                raise PostfixFormatException("Insufficient operands")
            val1 = stack.pop()
            val2 = stack.pop()
            if item == '/' and val1 == '0' or val1 == '0.0':
                raise ValueError
            if (item == '>>' or item == '<<') and (val1.find('.') != -1
                                                   or val2.find('.') != -1):
                raise PostfixFormatException("Illegal bit shift operand")
            stack.push(str(eval(val2 + item + val1)))
    res = stack.pop()
    if stack.num_items > 0:
        raise PostfixFormatException("Too many operands")
    if res.find('.') is not -1:
        return float(res)
    else:
        return int(res)
Esempio n. 4
0
def prefix_to_postfix(input_str):
    """Converts a prefix expression to an equivalent postfix expression"""
    input_list=input_str.split()
    reverse_list=input_list[::-1]
    s=Stack(30)
    for item in reverse_list:
        if isNumber(item):
            s.push(item)
        if item == '+' or item == '-' or item == '*' or item == '/' or item == '^':
            op1=s.pop()
            op2=s.pop()
            s.push(op1 + ' ' + op2 + ' ' + item)
    return(s.pop())

    # """Input argument: a string containing a prefix expression where tokens are
    # space separated.  Tokens are either operators + - * / ^ parentheses ( ) or numbers
    # Returns a String containing a postfix expression(tokens are space separated)"""


#print(infix_to_postfix("2 * 3 * ( 4 + 5 )"))
#print(infix_to_postfix("3 + 4 - 2 + ( 7 ^ 2 )"))
#print(infix_to_postfix("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"))
#print(postfix_eval("5 2 4 * + 7 + 2 - 4 6 2 / 2 - * + 4 -"))
#print(postfix_eval("99 38 1.2 * 3.6 2.8 / + 6 - 3.7 2 / 5 / + 3 - 23 + 1.1 / 2.2 + 2.4 5 / - 1 - 1.6 3 / 9 / 2.8 * 3 - 6.2 4 / 12.8 2 * 1.1 / 4.4 3.2 1.1 5.2 / 9.9 * - / - + - +"))
#print(infix_to_postfix("6 + 6 * 6 + 2 + 7 - 5 - ( 1 * 8 * 6 + 4 * 7 ^ 2 / 9 ^ 1 ^ 2 / 3 ) ^ 3 + 4 ( 8 ^ 6 ) * 7 * 2 - 8 ^ 8 ^ 9 - 7 + 6 + 6 ^ 4 ^ 6 - 4 ( 3 + 6 ) + 3 * 5 / 8 - 2 ^ 9 / 4 ^ 2 * ( 4 * 9 + 3 - 3 / 5 ^ 3 - 1 ) + 2 - 4 ^ 9" ))
Esempio n. 5
0
def prefix_to_postfix(input_str):
    """Converts a prefix expression to an equivalent postfix expression"""
    """Input argument: a string containing a prefix expression where tokens are 
    space separated.  Tokens are either operators + - * / ^ parentheses ( ) or numbers
    Returns a String containing a postfix expression(tokens are space separated)"""
    s = Stack(30)
    tokens = input_str.split()
    i = len(tokens) - 1
    operators = ['+', '-', '*', '/', '<<', '>>', '**']
    if input_str == '':
        return ''
    while i >= 0:
        char = tokens[i]
        if char.lstrip('-').replace('.', '', 1).isdigit():
            s.push(char)
            i -= 1
        elif char in operators:
            op1 = s.pop()
            op2 = s.pop()
            inf = op1 + ' ' + op2 + ' ' + char
            s.push(inf)
            i -= 1
        else:
            break
    return s.pop()
def postfix_eval(input_str):
    """Evaluates a postfix expression"""
    """Input argument:  a string containing a postfix expression where tokens 
    are space separated.  Tokens are either operators + - * / ** << >> or numbers (integers or floats)
    Returns the result of the expression evaluation. 
    Raises an PostfixFormatException if the input is not well-formed"""
    if input_str is None: raise PostfixFormatException
    # create list of operands and operators
    term_list = input_str.split()
    # initialize stack large enough to contain all operands
    operand_stack = Stack(2 * len(term_list) // 3 + 1)
    # iterate over term_list
    for term in term_list:
        # check for operatorm, evaluate operators on A & B if True
        if operator_present(term) is True:
            if operand_stack.size() < 2:
                raise PostfixFormatException("Insufficient operands")
            B = operand_stack.pop()
            A = operand_stack.pop()
            operand_stack.push(calculate(
                A,  # A
                B,  # B
                term)  # operator
                               )
        # check for operand, push to stack if True
        elif operand_present(term) is True:
            operand_stack.push(term)
        else:
            raise PostfixFormatException("Invalid token")
    if len(term_list) % 3 != 0:
        raise PostfixFormatException("Too many operands")
    return operand_stack.pop()
Esempio n. 7
0
def postfix_eval(input_str):
    inputList = input_str.split()
    postStack = Stack(30)
    for character in inputList:
        try:
            float(character)
        except:
            if character not in ['<<', '>>', '**', '*', '/', '+', '-']:
                raise PostfixFormatException("Invalid token")
            else:
                pass
    for item in inputList:
        try:
            postStack.push(int(item))
        except ValueError:
            try:
                postStack.push(float(item))
            except:
                if postStack.size() >= 2:
                    postStack.push(
                        doMath(postStack.pop(), postStack.pop(), item))
                else:
                    raise PostfixFormatException('Insufficient operands')
    if postStack.size() != 1:
        raise PostfixFormatException("Too many operands")
    return postStack.pop()
Esempio n. 8
0
def infix_to_postfix(input_str):
    """Converts an infix expression to an equivalent postfix expression"""
    """Input argument:  a string containing an infix expression where tokens are 
    space separated.  Tokens are either operators + - * / ** parentheses ( ) or numbers
    Returns a String containing a postfix expression """
    output = []
    stack = Stack(30)
    input = input_str.split()
    for item in input:
        if item.isnumeric():
            output.append(item)
        elif item == '(':
            stack.push(item)
        elif item == ')':
            while ((not stack.is_empty()) and (stack.peek() != '(')):
                val1 = stack.pop()
                output.append(val1)
            try:
                stack.pop()
            except:
                raise PostfixFormatException("Insufficient operands")
        # an operator is encountered
        else:
            while ((not stack.is_empty()) and orderOfOperations(stack, item)):
                output.append(stack.pop())
            stack.push(item)
    # pop all the operator from the stack
    while not stack.is_empty():
        output.append(stack.pop())
    return " ".join(output)
Esempio n. 9
0
def infix_to_postfix(input_str):
    """Converts an infix expression to an equivalent postfix expression"""
    """Input argument:  a string containing an infix expression where tokens are 
    space separated.  Tokens are either operators + - * / ^ parentheses ( ) or numbers
    Returns a String containing a postfix expression """

    stack = Stack(30)  # Stack of size 30
    operators = ["(", ")", ">>", "<<", "**", "*", "/", "+",
                 "-"]  # Allowed operands
    final_list = ""
    first_run = True

    split_string = input_str.split(
    )  # Split input string into usable chunks in a list

    for val in split_string:  # Run through every value in list in order

        if val == "(":
            stack.push("(")
        elif val == ")":
            popping = True
            while popping:
                popped_value = stack.pop()
                if popped_value == "(":
                    popping = False
                else:
                    final_list += " " + popped_value
        elif val in operators:
            popping = True
            while popping:
                if stack.is_empty():
                    popping = False
                elif stack.peek() == "(":
                    popping = False
                elif (val == ">>"
                      or val == "<<") and operators.index(stack.peek()) > 3:
                    popping = False
                elif val == "**" and operators.index(stack.peek()) > 3:
                    popping = False
                elif (val == "*"
                      or val == "/") and operators.index(stack.peek()) > 6:
                    popping = False
                else:
                    final_list += " " + stack.pop()
            stack.push(val)
        else:
            if first_run:
                final_list += str(val)
                first_run = False
            else:
                final_list += " " + str(val)

    popping = True
    while popping:
        if stack.is_empty():
            popping = False
        else:
            final_list += " " + stack.pop()

    return final_list
Esempio n. 10
0
def testInfix(inputString):
    inputList = inputString.split()
    rpnString = ''
    infixStack = Stack(30)
    for item in inputList:
        if item.isdigit():
            rpnString += item
        else:
            try:
                rpnString += str(float(item))
            except:
                pass
        if infixStack.size() > 0:
            o1 = item
            o2 = infixStack.peek()
            if o1 != '**':
                if getPrecVal(o1) <= getPrecVal(o2) and infixStack.size() > 0:
                    rpnString += infixStack.pop()
            elif o1 == '**':
                if getPrecVal(o1) < getPrecVal(o2) and infixStack.size() > 0:
                    rpnString += infixStack.pop()
            infixStack.push(item)
    for i in range(infixStack.size()):
        rpnString += infixStack.pop()
    return rpnString
Esempio n. 11
0
def infix_to_postfix(input_str):
    """Converts an infix expression to an equivalent postfix expression"""
    """Input argument:  a string containing an infix expression where tokens are 
    space separated.  Tokens are either operators + - * / ^ parentheses ( ) or numbers
    Returns a String containing a postfix expression """
    stack = Stack(30)
    tokens = input_str.split(" ")
    RPN = ""
    for token in tokens:
        if is_int(token) or is_float(token):
            if RPN == "":
                RPN = token
            else:
                RPN = RPN + " " + token
        elif token == "(":
            stack.push(token)
        elif token == ")":
            while stack.peek() != "(":
                RPN = RPN + " " + stack.pop()
            stack.pop()
        elif is_operator(token):
            while (stack.is_empty() == False) and is_operator(
                    stack.peek()) and has_precedence(token, stack.peek()):
                RPN = RPN + " " + stack.pop()
            stack.push(token)
    while stack.size() > 0:
        RPN = RPN + " " + str(stack.pop())
    return RPN
Esempio n. 12
0
def prefix_to_postfix(input_str):
    # creates a stack to store operators, operands, and joined expressions
    stack = Stack(30)
    # change the input string to a list of input operands and operators
    input_list = input_str.split()
    # creates a list to store the postfix expression
    output_list = []

    # steps through the input list in reverse
    for i in input_list[::-1]:
        # adds operands to the stack
        try:
            float(i)
            stack.push(i)
        except ValueError:
            # checks if i is an operator
            if i in ["+", "-", "*", "/", "**", "(", "<<", ">>"]:
                # removes the top two values of the stack and adds the operator i to the end
                val1 = stack.pop()
                val2 = stack.pop()
                add = val1 + " " + val2 + " " + i
                # adds the new expression to the stack
                stack.push(add)

    # after the loop goes through the entire input string,
    # all items in the stack are popped and added to the output postfix expression
    while stack.size() != 0:
        output_list.append(stack.pop())
    # joins the list of output characters into a string
    output = ' '.join(output_list)
    # returns the postfix expression
    return output
Esempio n. 13
0
def prefix_to_postfix(input_str):
    """Converts a prefix expression to an equivalent postfix expression"""
    """Input argument: a string containing a prefix expression where tokens are 
    space separated.  Tokens are either operators + - * / ** parentheses ( ) or numbers
    Returns a String containing a postfix expression(tokens are space separated)"""
    stack = Stack(30)
    operators = ['+', '-', '*', '/', '**']
    input = input_str.split()
    result = ""
    # Reversing the order
    input_reverse = input[::-1]
    # iterating through individual tokens
    for item in input_reverse:
        # if token is operator
        if item in operators:
            a = stack.pop()
            b = stack.pop()
            temp = a + b + item
            stack.push(temp)
        else:
            stack.push(item)
    # printing final output
    while not stack.is_empty():
        result = result + stack.pop()
    return " ".join(result)
Esempio n. 14
0
def prefix_to_postfix(input_str):
    '''Converts a prefix expression to an equivalent postfix expression
    Input argument:  a string containing a prefix expression where tokens are 
    space separated.  Tokens are either operators + - * / ** >> << parentheses ( ) or numbers
    Returns a String containing a postfix expression(tokens are space separated)'''
    op_lst = ["+", "-", "*", "/", "**"]  #list of operators
    val_lst = input_str.split(" ")  #list of individual tokens
    val_lst.reverse()
    stack = Stack(len(input_str))  #stack to push and pop our values
    if input_str == '':
        return ''
    for i in val_lst:
        if i not in op_lst:
            try:  #checks validity of tokens
                a = float(i)
                if str(abs(int(a))).isdigit(
                ):  #if i is a number i is pushed on to stack
                    stack.push(i)
            except ValueError:  #if cant't be casted as a float then its invalid
                raise PostfixFormatException("Invalid token")
        elif i in op_lst:
            try:  #checks to see if theres enough items to concatenate
                val1 = stack.pop()
                val2 = stack.pop()
            except IndexError:  #if an index error is raised from the stack then theres not enough items
                raise PostfixFormatException("Invalid Prefix Expression")
            result = str(val1) + " " + str(val2) + " " + i
            stack.push(result)
    if stack.size() == 1:
        return str(stack.pop())
    else:  #not enough operators
        raise PostfixFormatException("Invalid Prefix Expression")
Esempio n. 15
0
 def test_empty_stack(self):
     stack = Stack(0)
     with self.assertRaises(IndexError):
         stack.pop()
     with self.assertRaises(IndexError):
         stack.peek()
     with self.assertRaises(IndexError):
         stack.push(1)
Esempio n. 16
0
 def test2(self):
     stack2 = Stack(5)
     stack2.push(3)
     stacktest = Stack(0)
     self.assertEqual(stack2.pop(), 3)
     with self.assertRaises(IndexError):  #checks for exception
         stacktest.pop()
     with self.assertRaises(IndexError):  #checks for exception
         stacktest.peek()
 def test_pop(self):
     stack = Stack(3, [8, 12, 52])
     self.assertEqual(stack.pop(), 52)
     self.assertEqual(stack.pop(), 12)
     self.assertEqual(stack.num_items, 1)
     self.assertEqual(stack.pop(), 8)
     self.assertTrue(stack.is_empty())
     with self.assertRaises(IndexError):  # used to check for exception
         stack.pop()
 def test_size(self):
     stack1 = Stack(5)
     stack2 = Stack(3, [8, 12, 52])
     self.assertEqual(stack1.size(), 0)
     self.assertEqual(stack2.size(), 3)
     stack1.push(5)
     self.assertEqual(stack1.size(), 1)
     stack2.pop()
     self.assertEqual(stack2.size(), 2)
Esempio n. 19
0
def postfix_eval(input_str):
    """Evaluates a postfix expression"""
    """Input argument:  a string containing a postfix expression where tokens 
    are space separated.  Tokens are either operators + - * / ^ or numbers
    Returns the result of the expression evaluation. 
    Raises an PostfixFormatException if the input is not well-formed"""
    s = Stack(30)
    tokens = input_str.split()
    operators = ['+', '-', '*', '/', '**', '<<', '>>']
    if input_str == '':
        return ''
    for char in tokens:
        if char in operators:
            try:
                n2 = s.pop()
                n1 = s.pop()
            except IndexError:
                raise PostfixFormatException('Insufficient operands')
            if char == '+':
                result = n1 + n2
                s.push(result)
            if char == '-':
                result = n1 - n2
                s.push(result)
            if char == '*':
                result = n1 * n2
                s.push(result)
            if char == '/':
                if n2 == 0:
                    raise ValueError('Cannot divide by 0!')
                result = n1 / n2
                s.push(result)
            if char == '**':
                result = n1**n2
                s.push(result)
            if char == '<<':
                if type(n1) == float or type(n2) == float:
                    raise PostfixFormatException('Illegal bit shift operand')
                result = n1 << n2
                s.push(result)
            if char == '>>':
                if type(n1) == float or type(n2) == float:
                    raise PostfixFormatException('Illegal bit shift operand')
                result = n1 >> n2
                s.push(result)
        elif char.lstrip('-').replace('.', '', 1).isdigit():
            if '.' not in char:
                s.push(int(char))
            else:
                s.push(float(char))
        else:
            raise PostfixFormatException('Invalid token')
    final = s.pop()
    if not s.is_empty():
        raise PostfixFormatException('Too many operands')
    return final
Esempio n. 20
0
 def test4(self):
     stack = Stack(3)
     stack.push(None)
     self.assertEqual(stack.peek(), None)
     stack.push(3)
     stack.push(-2)
     stack.pop()
     stack.pop()
     stack.pop()
     self.assertEqual(stack.size(), 0)
Esempio n. 21
0
 def test_simple(self):
     stack = Stack(5)
     stack.push(0)
     self.assertFalse(stack.is_empty())
     self.assertFalse(stack.is_full())
     self.assertEqual(stack.size(), 1)
     stack.push(4)
     stack.push(9)
     self.assertEqual(stack.size(), 3)
     stack.push(8)
     stack.push(7)
     with self.assertRaises(IndexError):
         stack.push(6)
     stack.pop()
     self.assertEqual(stack.size(), 4)
     self.assertEqual(stack.peek(), 8)
     stack.pop()
     stack.pop()
     stack.pop()
     self.assertEqual(stack.pop(), 0)
     self.assertEqual(stack.size(), 0)
     with self.assertRaises(IndexError):
         stack.pop()
     with self.assertRaises(IndexError):
         stack.peek()
Esempio n. 22
0
def postfix_eval(input_str):
    # Evaluates a postfix expression
    # Input argument:  a string containing a postfix expression where tokens
    # are space separated.  Tokens are either operators + - * / ^ or numbers
    # Returns the result of the expression evaluation.
    # Raises an PostfixFormatException if the input is not well-formed

    #Delimiter
    postfixList = input_str.split(" ")
    #Creates Stack with capacity of the lenght of the delimited list
    postfixStack = Stack(len(postfixList))

    #For each element in the pfList
    for token in postfixList:
        try:
            #Try to push to stack if it is a number
            postfixStack.push(ast.literal_eval(token))
        except:
            #If a 'normal' operator is encountered
            if token in "*/+-^**":
                try:
                    #Pops the top two numbers on the stack then applies the
                    #token operator with pfMath()
                    numberTwo = postfixStack.pop()
                    numberOne = postfixStack.pop()
                    postfixStack.push(pfMath(token, numberOne, numberTwo))
                except:
                    #Checks for div 0 otherwise raises Insufficient operands
                    if numberTwo == 0:
                        raise ValueError("Undefined: Can't Divide By 0")
                    else:
                        raise PostfixFormatException("Insufficient operands")
            #For bit shift
            elif token in "<<>>":
                try:
                    #Attemps to pop top two on the stack
                    numberShifter = postfixStack.pop()
                    numberBase = postfixStack.pop()
                    #Left bit Shift
                    if token == "<<":
                        postfixStack.push(numberBase << numberShifter)
                    #Right bit Shift
                    else:
                        postfixStack.push(numberBase >> numberShifter)
                #Can't bit shift raise error
                except:
                    raise PostfixFormatException("Illegal bit shift operand")
            #Not a token or number
            else:
                raise PostfixFormatException("Invalid token")
    #End of postfixList checks what is on the stack
    if postfixStack.size() != 1:
        raise PostfixFormatException("Too many operands")
    #Returns the evaluated postfix
    return postfixStack.pop()
Esempio n. 23
0
def stack_test(a):
    """
    -------------------------------------------------------
    Tests 
    Use: stack_test(a)
    -------------------------------------------------------
    Preconditions:
        a - list of data (list of ?)
    Postconditions:
        the methods of Stack are tested for both empty and 
        non-empty stacks using the data in a:
        is_empty, push, pop, peek
    -------------------------------------------------------
    """
    s = Stack()

    # tests for the stack methods go here
    # print the results of the method calls and verify by hand
    print("is_empty for an empty stack:")
    is_empty = s.is_empty()
    print("{}".format(is_empty))
    try:
        print("pop empty:")
        pop = s.pop()
        print("{}".format(pop))
    except:
        print("pop empty failed")
    try:
        print("peek empty:")
        peek = s.peek()
        print("{}".format(peek))
    except:
        print("peek empty failed")
    try:
        print("push:")
        for j in a:
            s.push(j)
        for i in s:
            print("{}".format(i))
    except:
        print("push failed")
    try:
        print("pop:")
        pop = s.pop()
        print("{}".format(pop))
    except:
        print("pop failed")
    try:
        print("peek:")
        peek = s.peek()
        print("{}".format(peek))
    except:
        print("peek failed")
    return
Esempio n. 24
0
def postfix_eval(input_str):
    '''Evaluates a postfix expression
    Input argument:  a string containing a postfix expression where tokens
    are space separated.  Tokens are either operators + - * / ** >> << or numbers.
    Returns the result of the expression evaluation.
    Raises an PostfixFormatException if the input is not well-formed
    DO NOT USE PYTHON'S EVAL FUNCTION!!!'''
    if postfix_valid(input_str):
        numbers = Stack(30)
        input_list = input_str.split(" ")
        i = 0
        while i < len(input_list):
            type = type_check(input_list[i])
            if type == 0:
                numbers.push(input_list[i])
            else:
                if input_list[i] == "+":
                    a = float(numbers.pop())
                    b = float(numbers.pop())
                    numbers.push(a + b)
                elif input_list[i] == "-":
                    a = float(numbers.pop())
                    b = float(numbers.pop())
                    numbers.push(b - a)
                elif input_list[i] == "*":
                    a = float(numbers.pop())
                    b = float(numbers.pop())
                    numbers.push(a * b)
                elif input_list[i] == "/":
                    a = float(numbers.pop())
                    b = float(numbers.pop())
                    if a == 0:
                        raise ValueError
                    numbers.push(b / a)
                elif input_list[i] == "**":
                    a = float(numbers.pop())
                    b = float(numbers.pop())
                    numbers.push(b**a)
                elif input_list[i] == "<<":
                    a = float(numbers.pop())
                    b = float(numbers.pop())
                    if a == int(a) and b == int(b):
                        numbers.push(int(b) << int(a))
                    else:
                        raise PostfixFormatException(
                            "Illegal bit shift operand")
                elif input_list[i] == ">>":
                    a = float(numbers.pop())
                    b = float(numbers.pop())
                    if a == int(a) and b == int(b):
                        numbers.push(int(b) >> int(a))
                    else:
                        raise PostfixFormatException(
                            "Illegal bit shift operand")
            i += 1
        if int(numbers.peek()) == float(numbers.peek()):
            return int(numbers.pop())
        return numbers.pop()
Esempio n. 25
0
def infix_to_postfix(input_str):
    # Converts an infix expression to an equivalent postfix expression
    # Input argument:  a string containing an infix expression where tokens are
    # space separated.  Tokens are either operators + - * / ^ parentheses ( ) or numbers
    # Returns a String containing a postfix expression

    #Precedent
    orderOfOperations = {
        '<<': 5,
        '>>': 5,
        '^': 4,
        '**': 4,
        '*': 2,
        '/': 2,
        '+': 1,
        '-': 1,
        '(': 0
    }
    #Delimiter
    infixList = input_str.split(" ")
    #Sets up stack with capacity of the len of the delimited string
    opStack = Stack(len(infixList))
    #Output holder
    postfixOutput = []

    #For each element in the list of infix
    for token in infixList:
        try:
            #Using ast.literal_eval
            postfixOutput.append(ast.literal_eval(token))
        except:
            #Open ( push
            if token == "(":
                opStack.push(token)
            #Close ) stack pop
            elif token == ")":
                head = opStack.pop()
                while head != "(":
                    postfixOutput.append(head)
                    head = opStack.pop()
            elif orderOfOperations[token] == 4:
                opStack.push(token)
            else:
                #When the stack isn't empty and the ooO on the stack is greater then the current ooO
                while not (opStack.is_empty()) and (
                        orderOfOperations[opStack.peek()] >=
                        orderOfOperations[token]):
                    postfixOutput.append(opStack.pop())
                opStack.push(token)
    while not (opStack.is_empty()):
        postfixOutput.append(opStack.pop())
    #Recreate the string join together
    return " ".join(str(pfUnit) for pfUnit in postfixOutput)
Esempio n. 26
0
 def test_simple_1(self):
     stack = Stack(3)
     self.assertRaises(IndexError, stack.peek)
     stack.push(0)
     stack.push(1)
     stack.push(2)
     self.assertRaises(IndexError, stack.push, 3)
     self.assertTrue(stack.is_full())
     self.assertEqual(stack.size(),3)
     stack.pop()
     stack.pop()
     self.assertEqual(stack.pop(), 0)
Esempio n. 27
0
def postfix_eval(input_str):
    '''Evaluates a postfix expression
    Input argument:  a string containing a postfix expression where tokens 
    are space separated.  Tokens are either operators + - * / ** >> << or numbers.
    Returns the result of the expression evaluation. 
    Raises an PostfixFormatException if the input is not well-formed
    DO NOT USE PYTHON'S EVAL FUNCTION!!!'''
    op_lst = ["+", "-", "*", "/", "**"]  #list of operators
    val_lst = input_str.split(" ")  #list of individual tokens
    stack = Stack(len(input_str))  #stack to push and pop our values
    if input_str == "":
        return ""  #basecase
    for i in val_lst:  #loops throught the input string
        if i not in op_lst:
            try:  #checks validity of tokens
                if i.isdigit():  #if i is a digit i is pushed on to stack
                    stack.push(int(i))
                else:  #pushes it as float
                    stack.push(float(i))
            except ValueError:  #if cant't be casted as a float then its invalid
                raise PostfixFormatException("Invalid token")
        elif i in op_lst:
            try:  #checks to see if theres enough values to do operation
                val2 = stack.pop()
                val1 = stack.pop()
            except IndexError:  #if an index error is raised from the stack then theres not enough values
                raise PostfixFormatException("Insufficient operands")
            if i == "+":
                result = val1 + val2
                stack.push(result)
            if i == "-":
                result = val1 - val2
                stack.push(result)
            if i == "/":
                if val2 == 0:
                    raise ValueError("float division by 0")
                else:
                    result = val1 / val2
                    stack.push(result)
            if i == "*":
                result = val1 * val2
                stack.push(result)
            if i == "**":
                result = val1**val2
                stack.push(result)
    if stack.size() == 1:
        return stack.pop()
    else:  #if stack has more than one item left after iteration of val_Lst then too many operands
        raise PostfixFormatException("Too many operands")
Esempio n. 28
0
def prefix_to_postfix(input_str):
    '''Converts a prefix expression to an equivalent postfix expression
    Input argument:  a string containing a prefix expression where tokens are
    space separated.  Tokens are either operators + - * / ** >> << or numbers
    Returns a String containing a postfix expression (tokens are space separated)'''
    input_list = input_str.split(" ")
    nums = Stack(30)
    for i in range(1, len(input_list) + 1):
        type = type_check(input_list[len(input_list) - i])
        if type == 0:
            nums.push(input_list[len(input_list) - i])
        else:
            nums.push(nums.pop() + " " + nums.pop() + " " +
                      input_list[len(input_list) - i])
    return nums.pop()
Esempio n. 29
0
 def test3(self):
     stack = Stack(2)
     with self.assertRaises(
             IndexError):  # uses context manager to check exception
         stack.pop()
     with self.assertRaises(
             IndexError):  # uses context manager to check exception
         stack.peek()
     stack.push(3)
     self.assertNotEqual(stack.peek(), 2)
     stack.push(2)
     self.assertEqual(stack.peek(), 2)
     with self.assertRaises(
             IndexError):  # uses context manager to check exception
         stack.push(7)
    def test_pop(self):
        """Empty stack will return indexError when popping"""
        stack = Stack(5, [])
        with self.assertRaises(IndexError):
            stack.pop()
        """Testing non-empty stacks, item is removed from the stack"""
        stack.push(-1000)
        self.assertEqual(stack.__repr__(), "Stack(5, [-1000])")
        self.assertEqual(stack.pop(), -1000)
        self.assertEqual(stack.__repr__(), "Stack(5, [])")

        stack2 = Stack(5, [1, 2, 3, 4, 5])
        self.assertEqual(stack2.__repr__(), "Stack(5, [1, 2, 3, 4, 5])")
        self.assertEqual(stack2.pop(), 5)
        self.assertEqual(stack2.__repr__(), "Stack(5, [1, 2, 3, 4])")
Esempio n. 31
0
def parse_arithmetic(expression):
  operations = Stack()
  numbers = Stack()

  for c in expression:
    if c == '(': pass
    elif c == '+' or c == '*':
      operations.push(c)
    elif c == ')':
      operator = operations.pop()
      value2 = numbers.pop()
      value1 = numbers.pop()
      if operator == '+':
        numbers.push(value1 + value2)
      elif operator == '*':
        numbers.push(value1 * value2)
    else:
      numbers.push(int(c))

  return numbers.pop()
Esempio n. 32
0
class TestStack(unittest.TestCase):

    def setUp(self):
        self.stack = Stack()

    def test_init(self):
        self.assertEqual(self.stack.get_size(), 0)
        new_stack = Stack("Bob")
        self.assertEqual(new_stack.get_size(), 1)

    def test_push(self):
        initial_size = self.stack.get_size()
        self.stack.push("Bob")
        self.assertEqual(self.stack.get_size(), initial_size + 1)

    def test_peek(self):
        self.stack.push("Adrian")
        self.stack.push("Bob")
        self.stack.push("Claire")
        self.assertEqual(self.stack.peek(), "Claire")

    def test_pop(self):
        self.stack.push("Adrian")
        self.stack.push("Bob")
        self.stack.push("Claire")
        initial_size = self.stack.get_size()
        popped_item = self.stack.pop()
        self.assertEqual(popped_item, "Claire")
        self.assertEqual(self.stack.get_size(), initial_size - 1)

    def test_clear(self):
        self.stack.push("Adrian")
        self.stack.push("Bob")
        self.stack.push("Claire")
        self.assertEqual(self.stack.get_size(), 3)
        self.stack.clear()
        self.assertEqual(self.stack.get_size(), 0)

    def test_get_size(self):
        self.stack.push("Bob")
        self.assertEqual(self.stack.get_size(), 1)
Esempio n. 33
0
from stack_array import Stack

s = Stack()

print s.pop() # None
s.push('to')
s.push('be')
s.push('or')
s.push('not')
s.push('to')
print s.pop() # to
s.push('be')
print s.pop() # be
print s.pop() # not
s.push('that')
print s.pop() # that
print s.pop() # or
print s.pop() # be
s.push('is')