Created
October 26, 2014 07:46
-
-
Save avli/500d0ba1db8ba4c8a855 to your computer and use it in GitHub Desktop.
RPN calculator 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
# -*- coding: utf-8 -*- | |
""" | |
RPN calculator implementation. | |
""" | |
import math | |
import sys | |
def rpn(expr): | |
tokens, stack = expr.split(' '), [] | |
for tk in tokens: | |
if tk == '+': | |
stack = stack[:-2] + [stack[-2] + stack[-1]] | |
elif tk == '-': | |
stack = stack[:-2] + [stack[-2] - stack[-1]] | |
elif tk == '*': | |
stack = stack[:-2] + [stack[-2] * stack[-1]] | |
elif tk == '/': | |
stack = stack[:-2] + [stack[-2] / stack[-1]] | |
elif tk == '^': | |
stack = [stack[:-2] + stack[-2] ** stack[-1]] | |
elif tk == 'ln': | |
stack = stack[:-1] + [math.log([stack[-1]])] | |
elif tk == 'log10': | |
stack = stack[:-1] + [math.log10(stack[-1])] | |
else: | |
stack.append(float(tk)) | |
return stack[0] | |
def main(): | |
print rpn(sys.argv[1]) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment