class BalancedParentheses: def __init__(self): self.myStack = Stack(100) def AreParanthesesBalanced(self, expression): for c in expression: if (c == '[' or c == '{' or c == '('): self.myStack.push(c) if (c == ']' or c == '}' or c == ')'): if (self.myStack.isEmpty() or not self.ArePair(self.myStack.topElement(), c)): return False else: self.myStack.pop() if (self.myStack.isEmpty()): return True else: return False def ArePair(self, opening, closing): if (opening == '[' and closing == ']'): return True elif (opening == '{' and closing == '}'): return True elif (opening == '(' and closing == ')'): return True else: return False
class PrefixEvaluation: def __init__(self): self.myStack = Stack(100) # define stack of 100 elements def evaluatePrefix(self, expression): for c in reversed(expression): if (self.isOperand(c)): self.myStack.push(c) elif (self.isOperator(c)): oprand1 = self.myStack.pop() oprand2 = self.myStack.pop() result = self.performOperation(c, oprand1, oprand2) self.myStack.push(result) else: print("error!!!") return self.myStack.topElement() def isOperand(self, c): if (c >= '0' and c <= '9'): return True else: return False def isOperator(self, c): if (c == '+' or c == '-' or c == '*' or c == '/'): return True else: return False def performOperation(self, operator, oprand1, oprand2): if (operator == '+'): return int(oprand1) + int(oprand2) elif (operator == '-'): return int(oprand1) - int(oprand2) elif (operator == '*'): return int(oprand1) * int(oprand2) elif (operator == '/'): return int(oprand1) / int(oprand2) else: print("error!!!")
def test_stackOverflow(self): myStack = Stack(3) # declared a stack of size 3 myStack.push(5) myStack.push(5) myStack.push(5) self.assertEqual(myStack.push(5), "Stack full")
def test_push(self): myStack = Stack(10) self.assertEqual(myStack.push(5), "success")
def test_print(self): myStack = Stack(10) myStack.push(10) myStack.push(20) myStack.print()
def test_print_empty_stack(self): myStack = Stack(10) myStack.print()
def test_isNotEmpty(self): myStack = Stack(10) myStack.push(10) self.assertFalse(myStack.isEmpty())
def test_isEmpty(self): myStack = Stack(10) self.assertTrue(myStack.isEmpty())
def test_stackUnderflow(self): myStack = Stack(10) self.assertEqual(myStack.pop(), "Stack empty")
def test_pop(self): myStack = Stack(10) myStack.push(10) self.assertEqual(myStack.pop(), 10)
def test_topElement_stackEmpty(self): myStack = Stack(10) self.assertEqual(myStack.topElement(), "Stack empty")
def test_topElement(self): myStack = Stack(10) myStack.push(10) self.assertEqual(myStack.topElement(), 10)
def __init__(self): self.myStack = Stack(100) # define stack of 100 elements
def __init__(self): self.myStack = Stack(100)