用于评估算术表达式的程序

问题描述 投票:-1回答:1

这是一个我还没有解决的有趣问题。

给出Reverse Polish Notation中的算术表达式,编写一个程序对其求值。

该表达式作为数字和操作数的列表给出。例如,[5, 3, '+']应该返回5 + 3 = 8

例如,

[15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']

应该返回5,因为它等效于((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5

python algorithm arithmetic-expressions
1个回答
3
投票
ops = { "+": (lambda a, b: a + b), "-": (lambda a, b: a - b), "*": (lambda a, b: a * b), "/": (lambda a, b: a / b) } def pol(tokens): stack = [] for token in tokens: # Check if the current element is an operator if token in ops: # Take the last two elements from the list arg2 = stack.pop() arg1 = stack.pop() # Execute an operation based on the current operator result = ops[token](arg1, arg2) # Append the result to the list in order to keep working with it stack.append(result) else: # If it is a number, just append in to the list stack.append(int(token)) return stack.pop() print(pol([15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']))
© www.soinside.com 2019 - 2024. All rights reserved.