fork download
  1. import math
  2. def reverse_polish(input_stack):
  3. f = {
  4. '+': lambda t, b: b + t,
  5. '-': lambda t, b: b - t,
  6. '*': lambda t, b: b * t,
  7. '/': lambda t, b: b / t,
  8. '//':lambda t, b: b // t,
  9. '%': lambda t, b: b % t,
  10. '^': lambda t, b: b ** t}
  11. short_stack = []
  12. for i in input_stack:
  13. if i == '!':short_stack.append(math.factorial(short_stack.pop()))
  14. elif i in f:
  15. t, b = short_stack.pop(), short_stack.pop()
  16. short_stack.append(f[i](t, b))
  17. else:short_stack.append(float(i))
  18. return short_stack[0] if len(short_stack) == 1 else 'failed'
  19.  
  20. print(reverse_polish("0.5 1 2 ! * 2 1 ^ + 10 + *".split()))
  21. print(reverse_polish("1 2 3 4 ! + - / 100 *".split()))
  22. print(reverse_polish("100 807 3 331 * + 2 2 1 + 2 + * 5 ^ * 23 10 558 * 10 * + + *".split()))
  23.  
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
7.0
-4.0
18005582300.0