Guest User

Untitled

a guest
Jun 24th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. # a simple reverse-polish notation calculator
  2. #
  3. # shouldn't be too hard to extend this--variables seem like a natural progression
  4.  
  5. import operator
  6.  
  7. def error_string(token, values):
  8. plural = ''
  9. if values > 1:
  10. plural = 's'
  11.  
  12. return 'Error: %s takes %d value%s.' % (token, values, plural)
  13.  
  14. stack = []
  15. operators = {
  16. '+': [operator.add, 2],
  17. '-': [operator.sub, 2],
  18. '*': [operator.mul, 2],
  19. '/': [operator.div, 2],
  20. '^': [operator.pow, 2],
  21. '%': [operator.mod, 2],
  22. '_': [lambda x: -x, 1],
  23. }
  24.  
  25. if __name__ == '__main__':
  26. while True:
  27. expression = raw_input('# ')
  28.  
  29. if expression in ('q', 'quit', 'exit', ''):
  30. break
  31.  
  32. for token in expression.split():
  33. if token in operators:
  34. try:
  35. if operators[token][1] == 1:
  36. stack.append(operators[token][0](stack.pop()))
  37. elif operators[token][1] == 2:
  38. stack.append(operators[token][0](stack.pop(-2), stack.pop()))
  39. except:
  40. print error_string(token, operators[token][1])
  41. else:
  42. try:
  43. stack.append(float(token))
  44. except ValueError:
  45. print 'Error: only real numbers or %s.' % ''.join(operators.keys())
  46.  
  47. if len(stack) == 1:
  48. print str(stack.pop())
  49. else:
  50. print 'Error: badly formed.'
Add Comment
Please, Sign In to add comment