Skip to content

Instantly share code, notes, and snippets.

@ev0rtex
Created May 6, 2018 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ev0rtex/49703a4a383532ab0443abf0d9911314 to your computer and use it in GitHub Desktop.
Save ev0rtex/49703a4a383532ab0443abf0d9911314 to your computer and use it in GitHub Desktop.
Python RPN calculator implementation
#!/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()
@ev0rtex
Copy link
Author

ev0rtex commented May 6, 2018

INPUT:

EXPR > 1.5 45 * 9 / 12 +

OUTPUT:

19.5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment