python数据结构之转后缀表达式计算(栈的应用)

Posted ares-python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python数据结构之转后缀表达式计算(栈的应用)相关的知识,希望对你有一定的参考价值。

此只支持十以内的计算,所以如果需要通用的话还需改进!!!

from Stack import *


def funcations(n):
    po=[]
    stack=Stack()
    for i in range(len(n)):
        po.append(n[i])
    for token in po:
        if token in 0123456789:
            stack.push(int(token))
        else:
            operation_1=stack.pop()
            operation_2=stack.pop()
            result=math(operation_1,operation_2,token)
            stack.push(int(result))
    return stack.get_stack()

def math(op1,op2,token):
    if token==+:
        return op1+op2
    elif token==-:
        return op2-op1
    elif token==*:
        return op1*op2
    else:
        return op2/op1


if __name__ == __main__:
    n=543*-
    print(funcations(n))

 

以上是关于python数据结构之转后缀表达式计算(栈的应用)的主要内容,如果未能解决你的问题,请参考以下文章