fork download
  1. import operator as op
  2.  
  3. table = {'+' : op.add, '-' : op.sub, '*' : op.mul, '/' : op.truediv}
  4.  
  5. def rpn(exp):
  6. stack = []
  7. for token in exp.split():
  8. try: stack += [int(token)]
  9. except ValueError:
  10. try: stack += [float(token)]
  11. except ValueError:
  12. stack = stack[:-2] + [table[token](*stack[-2:])]
  13. return stack[-1]
  14.  
  15. if __name__ == '__main__':
  16. exp = "6.1 5.2 4.3 * + 3.4 2.5 / 1.6 * -"
  17. ans = rpn(exp)
  18. print("{0} = {1:.4f}".format(exp, ans))
  19.  
Success #stdin #stdout 0.02s 9444KB
stdin
Standard input is empty
stdout
6.1 5.2 4.3 * + 3.4 2.5 / 1.6 * - = 26.2840