Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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))
Add Comment
Please, Sign In to add comment