291_intermediate.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:dailyprogrammer 作者: vitkarpenko 项目源码 文件源码
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]
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号