def solve_rpn(expression):
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
'//': lambda x, y: x // y,
'%': lambda x, y: x % y,
'^': lambda x, y: x ** y
}
stack = collections.deque()
for token in expression.split():
if token == '!':
stack.append(math.factorial(stack.pop()))
elif token in operations:
arguments = [stack.pop(), stack.pop()][::-1]
stack.append(operations[token](*arguments))
else:
stack.append(float(token))
return stack[0]
评论列表
文章目录