实现说明
逻辑集中在函数 evaluate里。
文件的主干是一个循环——for token in tokens。
使用要点
evaluate是公开入口,文件里其余部分都是为它服务的内部实现。
常见问题
有语言之外需要解析的导入吗?
没有。每个导入都解析到语言自带的模块。 文件在加载时定义 evaluate。
签名一览:def evaluate(tokens: list[str]) -> int
核心语句
elif token == "-":
stack.append(left - right)
elif token == "*":
stack.append(left * right)
代码示例
def evaluate(tokens: list[str]) -> int:
stack: list[int] = []
operators = {"+", "-", "*", "/"}
for token in tokens:
if token in operators:
right = stack.pop()
left = stack.pop()
if token == "+":
stack.append(left + right)
elif token == "-":
stack.append(left - right)
elif token == "*":
stack.append(left * right)
else:
# postfix division truncates toward zero
stack.append(int(left / right))
else:
stack.append(int(token))
return stack.pop()
print(evaluate(["2", "3", "+"])) # 2 + 3
print(evaluate(["5", "1", "2", "+", "4", "*", "+", "3", "-"])) # 5 + (1 + 2) * 4 - 3
print(evaluate(["7", "2", "/"])) # truncating division