Guest User

Untitled

a guest
Jun 19th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. end_scripts = {"quit", "end", "q"}
  2. help_scripts = {"help", "h"}
  3.  
  4. help_doc = """
  5. A reverse polish or postfix calculator evaluates two numbers by the next opertion.
  6. For example, the sum of 4 and 5 can be found by entering: 5 4 +
  7.  
  8. Available operations include
  9.  
  10. + addition
  11. - subtraction
  12. * multiplication
  13. / division
  14. % modulo
  15. ^ exponential
  16.  
  17. Try finding the answer to 20 3 + 9 * 2 /
  18. """
  19.  
  20. operations = {
  21. "+" : (lambda a, b: a+b),
  22. "-" : (lambda a, b: a-b),
  23. "*" : (lambda a, b: a*b),
  24. "/" : (lambda a, b: a/b),
  25. "%" : (lambda a, b: a%b),
  26. "^" : (lambda a, b: a**b)
  27. }
  28.  
  29. acceptable_inputs = [str(i) for i in range(0,10)] +list(operations.keys()) +[" "]
  30.  
  31. def ok_input(instructions):
  32. for character in instructions:
  33. if character not in acceptable_inputs:
  34. return False
  35. return True
  36.  
  37. def interpret(raw_instructions):
  38. instructions_as_list = raw_instructions.strip().split()
  39. return instructions_as_list
  40.  
  41. def solve(instructions):
  42. stack = []
  43.  
  44. for token in instructions:
  45. if token in operations:
  46. if len(stack) < 2:
  47. print("ERROR: Each operation requires at least 2 operands.")
  48. return None
  49. b = stack.pop()
  50. a = stack.pop()
  51. stack.append(operations[token](a,b))
  52. else:
  53. stack.append(float(token))
  54.  
  55. return stack.pop()
  56.  
  57. def simplify_format(output_number):
  58. if output_number == None:
  59. return ""
  60. decmials = 0
  61. if int(output_number) == float(output_number):
  62. decimals = 0
  63. else:
  64. decimals = 4
  65. return "{0:.{1}f}".format(output_number, decimals)
  66.  
  67. if __name__ == "__main__":
  68. print("REVERSE POLISH CALCULATOR\nFor help, type help[ENTER]\nTo quit, type quit[ENTER]")
  69. n = 0
  70. while True:
  71. instructions = input("rpn >> ")
  72. if instructions in end_scripts:
  73. break
  74. elif instructions in help_scripts:
  75. print(help_doc)
  76. elif not ok_input(instructions):
  77. print("ERROR: Please use only numbers and operators for calculations.")
  78. elif instructions == "":
  79. pass
  80. else:
  81. print(simplify_format(solve(interpret(instructions))))
  82. n += 1
  83. print("Bye! You preformed {} calculations.".format(n))
Add Comment
Please, Sign In to add comment