Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import cmd, sys
- class ReversePolishCalculator(cmd.Cmd):
- intro = "This is a simple RPN calculator."
- prompt = "Expr: "
- def onecmd (self, expr):
- if expr == "q" or expr == "quit":
- sys.exit(0)
- if expr == "?" or expr == "help":
- 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 + - * /.")
- return
- stack = []
- tokens = expr.split(" ")
- for token in tokens:
- try:
- # Append to stack as a number -- value
- stack.append(float(token))
- except Exception as e:
- # Can't convert to float -- operator?
- if len(stack) < 2:
- print("Syntax Error. Try n1 n2 op, where n1 and n2 are numbers and op is one of + - * /.")
- stack = []
- return
- if token == "+":
- stack.append(stack.pop() + stack.pop())
- elif token == "-":
- stack.append(stack.pop() - stack.pop())
- elif token == "*":
- stack.append(stack.pop() * stack.pop())
- elif token == "/":
- divisor, dividend = stack.pop(), stack.pop()
- stack.append(dividend / divisor)
- else:
- print("Only operations +-*/ are supported.")
- stack = []
- return
- print("==> {}".format(stack.pop()))
- if len(stack) > 0:
- stack = []
- print("[i] Only two operands are evaluated.")
- if __name__ == '__main__':
- ReversePolishCalculator().cmdloop()
Advertisement
Add Comment
Please, Sign In to add comment