
龙书学习过程代码记录--Python3.5(毕竟第一遍看书,书里面的例子全用python写的)
One
将中缀表达式翻译成后缀表达式↓
class Parser(object): def __init__(self): self.lookahead = (input("")).split(' ') self.lad = 0 def expr(self): self.term() while True and self.lad < len(self.lookahead): if self.lookahead[self.lad] == '+': self.match('+') self.term() print('+') elif self.lookahead[self.lad] == '-': self.match('-') self.term() print('-') else: return 0 def term(self): if self.lookahead[self.lad].isdigit(): print(self.lookahead[self.lad]+' ',end='') self.match(self.lookahead[self.lad]) else: print('syntax error') def match(self,t): if self.lookahead[self.lad] == t and self.lad < len(self.lookahead): self.lad += 1 else: print('syntax error') class Postfix(object): def main(self): parse = Parser() parse.expr() postfix = Postfix() postfix.main()
包含两个类:Parser、Postfix
类Parser中包含函数:expr、term、match
类Parser的属性:lookahead、lad //lookahead作为输入的元素将空格切去后的集合,lad当作下标,python不能单个输入字符只能这样了。
程序的执行从一个Postfix实例开始执行,且Postfix的main函数中实例化了一个Parser对象。
Parser对象实例时会自动调用输入进lookahead,接着就可以通过三个函数之间的相互调用完成中缀表达式到后缀表达式的翻译。