コード例 #1
0
 def test_eq(self):
     stack1 = Stack(5)
     stack2 = Stack(5)
     stack3 = Stack(10)
     stack4 = Stack(5,[1, 2])
     self.assertEqual(stack1, stack2)
     self.assertNotEqual(stack1, stack3)
     self.assertNotEqual(stack1, stack4)
コード例 #2
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)
コード例 #3
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")
コード例 #4
0
 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())
コード例 #5
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 (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()
コード例 #6
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
コード例 #7
0
    def test_init(self):
        stack = Stack(5)
        self.assertEqual(stack.items, [None]*5)
        self.assertEqual(stack.capacity, 5)

        stack = Stack(5, [1, 2])
        self.assertEqual(stack.items[0:2], [1, 2])
        self.assertEqual(stack.capacity, 5)

        with self.assertRaises(IndexError):
            Stack(5, [1, 2, 3, 4, 5, 6])
コード例 #8
0
 def test_is_full(self):
     """Creating and testing full stack"""
     stack = Stack(6, [5, 4, 3, 2, 1, 0])
     self.assertEquals(stack.is_full(), True)
     """Testing non-full stacks"""
     stack2 = Stack(6)
     self.assertEquals(stack2.is_full(), False)
     stack3 = Stack(6, [1])
     self.assertEquals(stack3.is_full(), False)
コード例 #9
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()
コード例 #10
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)
コード例 #11
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
コード例 #12
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:
        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
コード例 #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)"""
    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()
コード例 #14
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" ))
コード例 #15
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)
コード例 #16
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
コード例 #17
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)
コード例 #18
0
    def test_push(self):
        """Creating non-full stack"""
        stack = Stack(5, [1, 2, 4])
        """Pushing 5 then -1 on non-full stack"""
        stack.push(5)
        self.assertEqual(stack.__repr__(), "Stack(5, [1, 2, 4, 5])")
        self.assertEqual(stack.items[0:4], [1, 2, 4, 5])
        self.assertEqual(stack.capacity, 5)

        stack.push(-1)
        self.assertEqual(stack.__repr__(), "Stack(5, [1, 2, 4, 5, -1])")
        self.assertEqual(stack.items[0:5], [1, 2, 4, 5, -1])
        self.assertEqual(stack.capacity, 5)
        """Stack is full, now testing indexError when calling push"""
        with self.assertRaises(IndexError):
            stack.push(0)
コード例 #19
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
コード例 #20
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)
コード例 #21
0
 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)
コード例 #22
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()
コード例 #23
0
 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()
コード例 #24
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
コード例 #25
0
 def test_is_empty(self):
     """Creating and testing empty stack"""
     stack = Stack(5)
     self.assertEquals(stack.is_empty(), True)
     """Testing non-empty stack"""
     stack2 = Stack(5, [5, 4, 3, 2])
     self.assertEquals(stack2.is_empty(), False)
コード例 #26
0
ファイル: exp_eval.py プロジェクト: IsraelBanez/Project2
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 (integers or floats)
    Returns a String containing a postfix expression(tokens are space separated)"""
    stack_hold = Stack(30)
    tokens = input_str.split()
    if len(input_str) == 0:
        return ''
    for i in range(len(tokens), 0, -1):
        if numeric(tokens[i - 1]) is False:
            first = stack_hold.pop()
            second = stack_hold.pop()
            ad = first + ' ' + second + ' ' + tokens[i - 1]
            stack_hold.push(ad)
        else:
            stack_hold.push(tokens[i - 1])
    return stack_hold.pop()
コード例 #27
0
ファイル: exp_eval.py プロジェクト: ashleysutter/Project2
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)
    tokens = input_str.split(" ")
    tokens.reverse()
    if input_str == "":
        return ""
    for token in tokens:
        if is_int(token) or is_float(token):
            stack.push(token)
        if is_operator(token) and (stack.size() > 1):
            a = stack.pop()
            b = stack.pop()
            c = a + " " + b + " " + token
            stack.push(c)
    return stack.pop()
コード例 #28
0
ファイル: exp_eval.py プロジェクト: nawachte/DataStructures
def prefix_to_postfix(input_str):
    inputList = input_str.split()
    inputList = inputList[::-1]
    prefixStack = Stack(30)
    for item in inputList:
        try:
            prefixStack.push(int(item))
        except:
            try:
                prefixStack.push(float(item))
            except:
                op1 = str(prefixStack.pop())
                op2 = str(prefixStack.pop())
                if op1[-1] == ' ':
                    op1 = op1[:-1]
                if op2[-1] == ' ':
                    op2 = op2[:-1]
                opString = op1 + ' ' + op2 + ' ' + str(item) + ' '
                prefixStack.push(opString)
    returnString = str(prefixStack.pop())
    if returnString[-1] == ' ':
        returnString = returnString[:-1]
    return returnString
コード例 #29
0
ファイル: exp_eval.py プロジェクト: baileywickham/college
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)"""
    rstr = input_str[::-1].split(' ')
    s = Stack(len(rstr) + 1)  # I hope no one sees this
    retstr = ''
    for char in rstr:
        if num(char):
            s.push(char)
        elif opp(char):
            op1 = s.pop()
            op2 = s.pop()
            s.push(f'{retstr} {op1} {op2} {char}')
    return ' '.join(s.pop().split())
コード例 #30
0
ファイル: exp_eval.py プロジェクト: baileywickham/college
def postfix_eval(input_str):
    """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"""
    sep = input_str.split(" ")
    stack = Stack(len(sep)+1)  # bad practice but safe
    for char in sep:
        if num(char):
            stack.push(intorfloat(char))
        elif opp(char):
            if stack.size() < 2:
                raise PostfixFormatException('Insufficient operands')
            above = stack.pop()
            below = stack.pop()
            stack.push(do(above, below, char))
        else:
            raise PostfixFormatException("Invalid token")
    if stack.size() > 1:
        raise PostfixFormatException("Too many operands")
    final = stack.pop()
    final = int(final) if final % 1 == 0 else final
    return final
コード例 #31
0
 def setUp(self):
     self.stack = Stack()
コード例 #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
 def test_init(self):
     self.assertEqual(self.stack.get_size(), 0)
     new_stack = Stack("Bob")
     self.assertEqual(new_stack.get_size(), 1)
コード例 #34
0
ファイル: stack-test.py プロジェクト: stevenlundy/pu-algos-1
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')
コード例 #35
0
ファイル: dijksta.py プロジェクト: stevenlundy/pu-algos-1
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()