<p>使用堆栈计算后缀符号。当你看到一个数字,你就把它推到堆栈上。当你看到一个操作符时,你弹出足够多的数字来满足它并推送结果。最后,堆栈应该只有一个项目,您可以打印它。你知道吗</p>
<p>现在通常<code>+</code>是一个二进制运算符:它需要两个操作数。在您的情况下,您希望它消耗堆栈上的任何内容。对于<code>+</code>来说,这是一个非常规的含义,但它的实现非常简单。你知道吗</p>
<pre><code>def postfix(tokens):
stack = []
tokens = tokens.split() if isinstance(tokens, str) else tokens
for token in tokens:
if token.isdigit() or token.startswith("-") and token[1:].isdigit():
stack.append(int(token))
elif token == "+":
assert stack # need at least one item
result = 0
while stack:
result += stack.pop()
stack.append(result)
else:
raise ValueError("invalid token {}".format(token))
assert len(stack) == 1
return stack[0]
print(postfix("1 2 3 +"))
</code></pre>
<p>这种结构很容易扩展到处理其他操作。例如,可以使用<code>+</code>进行二进制加法,<code>++</code>进行全和运算。你知道吗</p>
<pre><code>elif token == "++": # sum all
result = 0
while stack:
result += stack.pop()
stack.append(result)
elif token == "+": # binary additon
stack.append(stack.pop() + stack.pop())
</code></pre>