Keine Beschreibung

bee 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. class Stack:
  2. def __init__(self):
  3. self.items = []
  4. def isEmpty(self):
  5. return len(self.items)==0
  6. def push(self, item):
  7. self.items.append(item)
  8. def pop(self):
  9. return self.items.pop()
  10. def peek(self):
  11. if not self.isEmpty():
  12. return self.items[len(self.items)-1]
  13. def size(self):
  14. return len(self.items)
  15. def postfixEval(postfixExpr):
  16. operandStack = Stack()
  17. tokenList =postfixExpr.split()
  18. for token in tokenList:
  19. if token in"0123456789":
  20. operandStack.push(int(token))
  21. else:
  22. operand2 =operandStack.pop()
  23. operand1 =operandStack.pop()
  24. result =doMath(token,operand1,operand2)
  25. operandStack.push(result)
  26. return operandStack.pop()
  27. def doMath(op, op1, op2):
  28. if op == "*":
  29. return op1 * op2
  30. elif op == "/":
  31. return op1 / op2
  32. elif op == "+":
  33. return op1 + op2
  34. else:
  35. return op1 - op2
  36. print(postfixEval('7 8 + 3 2 + /'))