Skip to content

Instantly share code, notes, and snippets.

@tamago324
Last active August 30, 2020 14:10
Show Gist options
  • Save tamago324/59c551e98a92c5b4d94f26d73b89647b to your computer and use it in GitHub Desktop.
Save tamago324/59c551e98a92c5b4d94f26d73b89647b to your computer and use it in GitHub Desktop.
中置記法を後置記法に変換
""" 中置記法の数式を後置記法に翻訳する
ドラゴンブックの 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()
@tamago324
Copy link
Author

> py -3 infix2postfix.py 1+2+3
12+3+

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