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:
        empty, push, pop, peek
    -------------------------------------------------------
    """
    s = Stack()
    print("a: {}".format(a))
    #is_Empty
    print("Tests s.is_Empty: {}".format(s.is_empty()))
    array_to_stack(s, a)
    print("Tests s.is_Empty again: {}".format(s.is_empty()))
    print("Stack after array_to_stacks: ")
    for v in s:
        print(v)
    #push
    print("Pushes '21' to the top of the stack: ")
    s.push(21)
    #pop
    print("Tests pop: {}".format(s.pop()))
    #peek
    print("Tests peek: {}".format(s.peek()))

    print("Stack to array: ")
    stack_to_array(s, a)
    print(a)
    return
示例#2
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
示例#3
0
 def test_simple(self):
     stack = Stack(5)
     self.assertRaises(IndexError, stack.pop)
     stack.push(0)
     self.assertFalse(stack.is_empty())
     self.assertFalse(stack.is_full())
     self.assertEqual(stack.size(),1)
示例#4
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")
示例#5
0
文件: q1.py 项目: Exacte/CP114
def postfix(s):
    """
    -------------------------------------------------------
    Evaluates a postfix expression string
    -------------------------------------------------------
    Preconditions:
       s - the postfix string to evaluate. Tokens are separated by
       spaces. Valid operators are +, -, *, /, **, %. Operands
       are assumed to be float. (str)
    Postconditions:
       Returns:
       answer - the result of evaluating s, None if the stack does
       not contain exactly one float value after evaluating s (float)
    -------------------------------------------------------
    """
    temp = ''
    stack = Stack()
    for i in range(len(s)):
        if s[i].isdigit() == True:
            temp += s[i]
        elif s[i] == " ":
            if s[i - 1] not in OP:
                stack.push(temp)
                temp = ''
        elif s[i] in OP:
            value1 = str(stack.pop())
            value2 = str(stack.pop())
            answer = eval(value2 + s[i] + value1)
            stack.push(answer)
            temp = ''
    return answer
示例#6
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
示例#7
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" ))
示例#8
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)
示例#9
0
def stack_split(s1):
    """
    -------------------------------------------------------
    Splits the given stack into separate stacks. Given stack is empty when
    function is done. Items are alternately pushed onto the returned stacks.
    Order is not significant.
    Use: s2, s3 = stack_split(s1)
    -------------------------------------------------------
    Preconditions:
        s1 - the stack to split into two parts (Stack)
    Postconditions:
        returns
        s2 - contains alternating values from given stack (Stack)
        s3 - contains other alternating values from given stack (Stack)
    -------------------------------------------------------
    """
    s2 = Stack()
    s3 = Stack()
    
    while s1.is_empty() != True:
        s2.push(s1.pop())
        if s1.is_empty() != True:
            s3.push(s1.pop())
        
    return s2, s3
示例#10
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)
示例#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
示例#12
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()
示例#13
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()))
示例#14
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
 def test_is_empty(self):
     stack1 = Stack(5)
     stack2 = Stack(3, [8, 12, 52])
     self.assertTrue(stack1.is_empty())
     self.assertFalse(stack2.is_empty())
     stack1.push(5)
     self.assertFalse(stack1.is_empty())
示例#16
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)

    #Delimiter + Reverse
    prefixString = list(reversed(input_str.split(" ")))
    #Stack setup with capacity equal to len of list
    prefixStack = Stack(len(prefixString))

    #For each element in the list
    for token in prefixString:
        #Token checker
        if token in "*/+-^**>><<":
            #Pops top 2 then assembles as postfix
            numberOne = prefixStack.pop()
            numberTwo = prefixStack.pop()
            tempString = numberOne + " " + numberTwo + " " + token
            #Pushes string back on the the stack
            prefixStack.push(tempString)
        else:
            prefixStack.push(token)
    #Returns the string accumulator
    return prefixStack.peek()
示例#17
0
 def test1(self):
     stack1 = Stack(1)
     stack1.push(2)
     self.assertFalse(stack1.is_empty())
     self.assertTrue(stack1.is_full())
     with self.assertRaises(IndexError):  #checks for exception
         stack1.push(1)
示例#18
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)
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()
 def test_size(self):
     """Testing empty stack"""
     stack = Stack(3, [])
     self.assertEqual(stack.size(), 0)
     """testing non-empty stack"""
     stack.push(2)
     self.assertEqual(stack.size(), 1)
     self.assertNotEqual(stack.size(), stack.capacity)
示例#21
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)
示例#22
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_is_full(self):
     stack1 = Stack(2)
     stack2 = Stack(3, [8, 12, 52])
     self.assertFalse(stack1.is_full())
     self.assertTrue(stack2.is_full())
     stack1.push(5)
     self.assertFalse(stack1.is_full())
     stack1.push(99)
     self.assertTrue(stack1.is_full())
示例#24
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(1)
     self.assertEqual(stack.pop(), 1)
     self.assertEqual(stack.peek(), 0)
 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)
示例#26
0
 def test3(self):
     stack3 = Stack(3)
     stack3.push(7)
     stack3.push(6)
     stack3.push(5)
     stacktest = Stack(0)
     self.assertEqual(stack3.peek(), 5)
     self.assertEqual(stack3.size(), 3)
     self.assertFalse(stack3.is_empty())
     self.assertTrue(stacktest.is_empty())
示例#27
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
示例#28
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)
示例#29
0
def mirror_stack(s, valid_chars, m):
    """
    -------------------------------------------------------
    Determines if string is a mirror of characters in valid_chars around the pivot m.
    A mirror is of the form LmR, where L is the reverse of R, and L and R
    contain only characters in valid_chars.
    Use: is_mirror = mirror_stack(string, valid_chars, m)
    -------------------------------------------------------
    Preconditions:
        string - a string (str)
        valid_chars - a string of valid characters (str)
        m - the mirror pivot string (str - one character not in valid_chars)
    Postconditions:
        returns
        is_mirror (int) - one of:
            IS_MIRROR - string is of the form LmR
            BAD_CHAR - L or R contains characters not in valid_chars
            NO_MIRROR - string does not contain m
            MORE_LEFT - too many characters in L
            MORE_RIGHT - too many characters in R
            MISMATCHED -  some characters in L and R don't match
    -------------------------------------------------------
    """
    stack = Stack()

    is_mirror = (len(s) == 0 or len(s) % 2 == 0)
    i = 0
    
    while is_mirror and i < len(s) and s[i] != m:
        if s[i] in valid_chars:
            stack.push(s[i])
            i+=1
        else:
            is_mirror = BAD_CHAR
        i +=1
    
    i +=1
    
    while is_mirror and i < len(s) and not stack.isempty():
        val = stack.pop()
        if val!= s[i]:
            is_mirror = MISMATCHED
        else:
            i+=1
    if not stack.is_empty():
        is_mirror = MORE_LEFT
    elif i < len(s) and stack.is_empty():
        is_mirror = MORE_RIGHT     
    
    return is_mirror
示例#30
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()
示例#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()
示例#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)
示例#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')