Last active
February 22, 2019 02:15
-
-
Save TylerJWhit/991af51ab05b3a7942c3758e9bf194e3 to your computer and use it in GitHub Desktop.
RPN Calculator
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
# TylerJWhit | |
# RPN Calculator | |
# 2019.02.21 | |
# Example: | |
# python3 rpn.py 3 47 22 + - | |
import sys | |
import argparse | |
def get_argument_parser(): | |
parser = argparse.ArgumentParser('This program is an RPN Calculator') | |
parser.add_argument('calc' , nargs = '*', type = str) | |
return parser | |
def parse_arguments(): | |
parser = get_argument_parser() | |
parsed = parser.parse_args(sys.argv[1:]) | |
return parsed | |
def process(action, first, second): | |
print(first, action, second) # Helps user to know the calculation logic | |
operands = { | |
'+' : lambda: first + second, | |
'-' : lambda: first - second, | |
'*' : lambda: first * second, | |
'/' : lambda: first / second | |
} | |
run = operands.get(action, lambda: "Not a valid operand") | |
return run() | |
def main(): | |
args = parse_arguments() | |
numbers = [] | |
result = None | |
for i in args.calc: | |
if i.isnumeric(): | |
numbers.append(int(i)) | |
else: | |
result = process(i, numbers.pop(), numbers.pop()) | |
# Helps to not carry values to just append. Also how RPN logic works. | |
numbers.append(result) | |
print(result) | |
if __name__ == '__main__': |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment