FLamparski

RPN simple

Sep 5th, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import cmd, sys
  4.  
  5. class ReversePolishCalculator(cmd.Cmd):
  6.     intro = "This is a simple RPN calculator."
  7.     prompt = "Expr: "
  8.  
  9.     def onecmd (self, expr):
  10.         if expr == "q" or expr == "quit":
  11.             sys.exit(0)
  12.         if expr == "?" or expr == "help":
  13.             print("Enter a simple math expression in Reverse Polish Notation, such as n1 n2 op, where n(1,2) are numbers and op is one of + - * /.")
  14.             return
  15.  
  16.         stack = []
  17.         tokens = expr.split(" ")
  18.         for token in tokens:
  19.             try:
  20.                 # Append to stack as a number -- value
  21.                 stack.append(float(token))
  22.             except Exception as e:
  23.                 # Can't convert to float -- operator?
  24.                 if len(stack) < 2:
  25.                     print("Syntax Error. Try n1 n2 op, where n1 and n2 are numbers and op is one of + - * /.")
  26.                     stack = []
  27.                     return
  28.                 if token == "+":
  29.                     stack.append(stack.pop() + stack.pop())
  30.                 elif token == "-":
  31.                     stack.append(stack.pop() - stack.pop())
  32.                 elif token == "*":
  33.                     stack.append(stack.pop() * stack.pop())
  34.                 elif token == "/":
  35.                     divisor, dividend = stack.pop(), stack.pop()
  36.                     stack.append(dividend / divisor)
  37.                 else:
  38.                     print("Only operations +-*/ are supported.")
  39.                     stack = []
  40.                     return
  41.  
  42.                 print("==> {}".format(stack.pop()))
  43.                 if len(stack) > 0:
  44.                     stack = []
  45.                     print("[i] Only two operands are evaluated.")
  46.  
  47. if __name__ == '__main__':
  48.     ReversePolishCalculator().cmdloop()
Advertisement
Add Comment
Please, Sign In to add comment