Created
January 28, 2020 06:03
-
-
Save tomoyk/cbac3176c1048f6de1635590e9d254f0 to your computer and use it in GitHub Desktop.
逆ポーランド記法の構文解析やってみた
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
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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
実行結果: