Created
May 6, 2018 21:20
-
-
Save ev0rtex/49703a4a383532ab0443abf0d9911314 to your computer and use it in GitHub Desktop.
Python RPN calculator implementation
This file contains hidden or 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
#!/usr/bin/env python3 | |
import sys | |
import operator | |
from decimal import Decimal | |
def main(): | |
ops = { | |
"+": operator.add, | |
"-": operator.sub, | |
"*": operator.mul, | |
"/": operator.truediv | |
} | |
digit = set("0123456789.") | |
stack = [] | |
for part in input("EXPR > ").strip().split(' '): | |
if set(part).issubset(digit): | |
stack.append(part) | |
elif part in ops: | |
if len(stack) < 2: | |
print("Two operands needed") | |
sys.exit(1) | |
else: | |
r = Decimal(stack.pop()) | |
l = Decimal(stack.pop()) | |
stack.append(ops[part](l, r)) | |
else: | |
print("Invalid character: {}".format(part)) | |
sys.exit(1) | |
print(stack.pop()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
INPUT:
OUTPUT: