Skip to content

Instantly share code, notes, and snippets.

@kevchentw
Created November 22, 2021 16:48
Show Gist options
  • Select an option

  • Save kevchentw/4e851c10758f8a6af22fa806499f6629 to your computer and use it in GitHub Desktop.

Select an option

Save kevchentw/4e851c10758f8a6af22fa806499f6629 to your computer and use it in GitHub Desktop.
def parse(s):
s = s.split(' ')[::-1]
stack = []
for i in s:
if i in ["+", "-", "*", "/"]:
a, b = stack.pop(), stack.pop()
if i == "+":
stack.append(a + b)
if i == "-":
stack.append(a - b)
if i == "*":
stack.append(a * b)
if i == "/":
stack.append(a / b)
else:
stack.append(int(i))
return stack[0]
assert parse("+ 1 / 4 2") == 3
assert parse("* - 10 5 2") == 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment