Skip to content

Instantly share code, notes, and snippets.

@pgassendi
Created August 24, 2022 00:53
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 pgassendi/327ebe111e71560349aef9742a112f37 to your computer and use it in GitHub Desktop.
Save pgassendi/327ebe111e71560349aef9742a112f37 to your computer and use it in GitHub Desktop.
Simple calculator using python
import sys
priority = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3,
'(': 0
}
opsfun = {
"+" : lambda x, y: x + y,
"-" : lambda x, y: x - y,
"*" : lambda x, y: x * y,
"/" : lambda x, y: x / y,
"^" : lambda x, y: x ** y
}
def read_number(s, i):
return next((k for k,e in enumerate(s[i+1:]) if e in " +-*/^()"), len(s[i:]) - 1) + i + 1
def read_string(s):
tokens = []
last = "^"
i = 0
while i < len(s):
if s[i] == " ":
i = i + 1
pass
elif s[i] in "+*/^()" or (s[i] == "-" and last in "0123456789)"):
tokens.append(s[i])
last = s[i]
i = i + 1
else:
ix = read_number(s,i)
tokens.append(s[i:ix])
last = s[ix-1]
i = ix
return tokens
def reduceWhile(ops, vals, condition):
while ops and condition(ops[-1]):
vals[-1] = opsfun[ops.pop()](vals[-2], vals.pop())
def calcu(tokens):
ops, vals = [], []
expr = read_string(tokens.strip())
for c in expr:
if (c == '('):
ops.append(c)
elif (c == ')'):
reduceWhile(ops, vals, lambda last: last != '(')
ops.pop()
elif c not in ["+", "-", "*", "/", "^"]:
vals.append(float(c))
else:
reduceWhile(ops, vals, lambda last: priority[c] <= priority[last])
ops.append(c)
reduceWhile(ops, vals, lambda x: True)
return vals[-1]
if __name__ == "__main__":
for line in sys.stdin:
print(calcu(line))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment