Exemplo n.º 1
0
def is_balanced(brackets):
    brackets = brackets.strip()
    if brackets == '':
        raise Exception("The string is empty")
    if '(' not in brackets and ')' not in brackets:
        raise Exception("This string without brackets")
    stack = Stack()
    for bracket in brackets:
        if bracket == ')' and stack.is_empty():
            print(
                "The string is started with closed bracket and it is  not balanced"
            )
            return False
        elif bracket == '(':
            stack.push(bracket)
        elif bracket == ')':
            stack.pop()
        else:
            raise Exception("This string has something else but brackets")
    if stack.is_empty():
        print("The string is balanced")
        return True
    else:
        print("The string is not balanced")
        return False
def calculate_postfix(expression):
    S = Stack()
    if not expression:
        raise Exception("The string is empty")
    for item in expression:
        if item.isdigit():
            S.push(int(item))
        elif item == "+":
            val1 = S.pop()
            val2 = S.pop()
            S.push(val1 + val2)
        elif item == "*":
            val1 = S.pop()
            val2 = S.pop()
            S.push(val1 * val2)
        elif item == "-":
            val1 = S.pop()
            val2 = S.pop()
            S.push(val1 - val2)
        elif item == "/":
            val1 = S.pop()
            val2 = S.pop()
            S.push(val1 / val2)

        elif item == "=":
            return S.pop()
    return S.pop()
 def test_pop_one_element(self):
     stack = Stack()
     stack.push(1)
     stack.pop()
     self.assertEqual(stack.tail, None)
     self.assertEqual(stack.head, None)
     self.assertEqual(stack.size(), 0)
 def test_pop_two_element(self):
     stack = Stack()
     stack.push(1)
     stack.push(2)
     self.assertEqual(stack.pop(), 2, "We should pop 2")
     self.assertEqual(stack.peek(), 1)
     self.assertEqual(stack.size(), 1)
     self.assertEqual(stack.pop(), 1, "We should pop 1")
     self.assertEqual(stack.size(), 0)
 def test_stack_peek(self):
     stack = Stack()
     stack.push(77)
     stack.push(123)
     self.assertEqual(stack.peek(), 123, "We should peek 123")
     self.assertEqual(stack.pop(), 123, "We hsould pop 123")
     self.assertEqual(stack.peek(), 77, "We should peek 77")
     self.assertEqual(stack.pop(), 77, "We should pop 77")
     self.assertEqual(stack.size(), 0)
     self.assertIsNone(stack.peek(), "peek is none")
 def addTail(self, item):
     Stack.push(self,item)
Exemplo n.º 7
0
 def enqueue(self, item):  #need to add element to the end of the list
     Stack.push(self, item)