Last active
August 30, 2020 14:10
-
-
Save tamago324/59c551e98a92c5b4d94f26d73b89647b to your computer and use it in GitHub Desktop.
中置記法を後置記法に変換
This file contains hidden or 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
""" 中置記法の数式を後置記法に翻訳する | |
ドラゴンブックの p81 のコードを Python で書いた | |
再帰あり ver | |
""" | |
import string | |
from typing import Optional | |
from sys import argv | |
class Parser: | |
def __init__(self, input_str: str): | |
self.input_str: str = input_str | |
self.pos = 0 | |
@property | |
def lookahead(self) -> Optional[str]: | |
""" 先読み文字 """ | |
# IndexError になるため | |
if self.pos >= len(self.input_str): | |
return None | |
return self.input_str[self.pos] | |
def expr(self) -> None: | |
self.term() | |
self.rest() | |
def rest(self) -> None: | |
if self.lookahead == "+": | |
# + | |
self.match("+") | |
self.term() | |
print("+", end="") | |
self.rest() | |
elif self.lookahead == '-': | |
# - | |
self.match("-") | |
self.term() | |
print("-", end="") | |
self.rest() | |
else: | |
# 空文字の規則 | |
pass | |
def term(self) -> None: | |
if self.lookahead is not None and self.lookahead in string.digits: | |
num = self.lookahead | |
self.match(self.lookahead) | |
print(num, end="") | |
else: | |
raise Exception("syntax error") | |
def next(self) -> None: | |
""" 入力文字を読みすすめる """ | |
self.pos += 1 | |
def match(self, t: str) -> None: | |
""" 先読み文字とマッチすれば、読みすすめる""" | |
if self.lookahead == t: | |
self.next() | |
else: | |
raise Exception("syntax error") | |
if __name__ == "__main__": | |
input_str = argv[1] | |
parse = Parser(input_str) | |
parse.expr() |
Author
tamago324
commented
Aug 30, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment