首页 > 编程语言 > 详细

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

时间:2020-05-04 14:27:01      阅读:74      评论:0      收藏:0      [点我收藏+]

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

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数据结构之转后缀表达式计算(栈的应用)

原文:https://www.cnblogs.com/ares-python/p/12826355.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!