Skip to content

Instantly share code, notes, and snippets.

@tomoyk
Created January 28, 2020 06:03
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 tomoyk/cbac3176c1048f6de1635590e9d254f0 to your computer and use it in GitHub Desktop.
Save tomoyk/cbac3176c1048f6de1635590e9d254f0 to your computer and use it in GitHub Desktop.
逆ポーランド記法の構文解析やってみた
in_txt = '13 5 4 + 3 / 4 * -'.split(' ')
symbols = ('+', '-', '*', '/')
stack = []
print("input::", ' '.join(in_txt))
for i,_ in enumerate(in_txt):
# FOUND NUM
if in_txt[i] not in symbols:
stack.append(int(in_txt[i]))
continue
# FOUND SYMBOL
cur = in_txt[i]
num1 = stack.pop()
num2 = stack.pop()
tmp = eval(f'{num2} {cur} {num1}')
stack.append(tmp)
print(f'{num2} {cur} {num1}')
print("stack::", stack)
print("answer::", stack[-1])
@tomoyk
Copy link
Author

tomoyk commented Jan 28, 2020

実行結果:

$ python3 reverse_polish_notation.py
input:: 13 5 4 + 3 / 4 * -
5 + 4
stack:: [13, 9]
9 / 3
stack:: [13, 3.0]
3.0 * 4
stack:: [13, 12.0]
13 - 12.0
stack:: [1.0]
answer:: 1.0

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