Created
October 4, 2013 22:59
-
-
Save nbari/6834265 to your computer and use it in GitHub Desktop.
A python 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
#!/usr/bin/env python | |
""" | |
https://gist.github.com/cammckinnon/3971894 | |
http://stackoverflow.com/questions/1740726/python-turn-string-into-operator | |
http://www.tutorialspoint.com/python/arithmetic_operators_example.htm | |
http://erezsh.wordpress.com/2012/11/18/how-to-write-a-calculator-in-50-python-lines-without-eval/ | |
""" | |
import re | |
import sys | |
class operators(object): | |
def add(self, x, y): | |
return x + y | |
def sub(self, x, y): | |
return x - y | |
def mul(self, x, y): | |
return x * y | |
def div(self, x, y): | |
return x / y | |
o = operators() | |
omap = { | |
'+': (lambda x,y: o.add(x, y)), | |
'-': (lambda x,y: o.sub(x, y)), | |
'*': (lambda x,y: o.mul(x, y)), | |
'/': (lambda x,y: o.div(x, y)), | |
} | |
def solve_term(tokens): | |
tokens = re.split('(/|\*)', tokens) | |
ret = float(tokens[0]) | |
for op, num in zip(tokens[1::2], tokens[2::2]): | |
num = float(num) | |
if op == '*': | |
ret = omap['*'](ret, num) | |
else: | |
ret = omap['/'](ret, num) | |
return ret | |
def main(args): | |
# remove whitespaces | |
tokens = re.sub('\s+', '', args) | |
# split by addition/subtraction operators | |
tokens = re.split('(-|\+)', tokens) | |
result = solve_term(tokens[0]) | |
for op, num in zip(tokens[1::2], tokens[2::2]): | |
num = float(num) | |
if op == '+': | |
result = omap['+'](result, num) | |
else: | |
result = omap['-'](result, num) | |
print result | |
if __name__ == "__main__": | |
main(''.join(sys.argv[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment