Created
June 18, 2018 04:02
-
-
Save t-eckert/f5b9be1a8781d9e2bfd32d959889d6e9 to your computer and use it in GitHub Desktop.
Reverse Polish Calculator for the command line. Written in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
end_scripts = {"quit", "end", "q"} | |
help_scripts = {"help", "h"} | |
help_doc = """ | |
A reverse polish or postfix calculator evaluates two numbers by the next opertion. | |
For example, the sum of 4 and 5 can be found by entering: 5 4 + | |
Available operations include | |
+ addition | |
- subtraction | |
* multiplication | |
/ division | |
% modulo | |
^ exponential | |
Try finding the answer to 20 3 + 9 * 2 / | |
""" | |
operations = { | |
"+" : (lambda a, b: a+b), | |
"-" : (lambda a, b: a-b), | |
"*" : (lambda a, b: a*b), | |
"/" : (lambda a, b: a/b), | |
"%" : (lambda a, b: a%b), | |
"^" : (lambda a, b: a**b) | |
} | |
acceptable_inputs = [str(i) for i in range(0,10)] +list(operations.keys()) +[" "] | |
def ok_input(instructions): | |
for character in instructions: | |
if character not in acceptable_inputs: | |
return False | |
return True | |
def interpret(raw_instructions): | |
instructions_as_list = raw_instructions.strip().split() | |
return instructions_as_list | |
def solve(instructions): | |
stack = [] | |
for token in instructions: | |
if token in operations: | |
if len(stack) < 2: | |
print("ERROR: Each operation requires at least 2 operands.") | |
return None | |
b = stack.pop() | |
a = stack.pop() | |
stack.append(operations[token](a,b)) | |
else: | |
stack.append(float(token)) | |
return stack.pop() | |
def simplify_format(output_number): | |
if output_number == None: | |
return "" | |
decmials = 0 | |
if int(output_number) == float(output_number): | |
decimals = 0 | |
else: | |
decimals = 4 | |
return "{0:.{1}f}".format(output_number, decimals) | |
if __name__ == "__main__": | |
print("REVERSE POLISH CALCULATOR\nFor help, type help[ENTER]\nTo quit, type quit[ENTER]") | |
n = 0 | |
while True: | |
instructions = input("rpn >> ") | |
if instructions in end_scripts: | |
break | |
elif instructions in help_scripts: | |
print(help_doc) | |
elif not ok_input(instructions): | |
print("ERROR: Please use only numbers and operators for calculations.") | |
elif instructions == "": | |
pass | |
else: | |
print(simplify_format(solve(interpret(instructions)))) | |
n += 1 | |
print("Bye! You preformed {} calculations.".format(n)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment