Python中缀表达式转后缀表达式并求值

Python中缀表达式转后缀表达式并求值

  话不多说直接上代码,代码注释中有大概的思路。

代码

import sys

'''中缀表达式转后缀表达式求值'''

'''逆波兰表达式求值过程
从左到右扫描后缀表达式
1.若是操作数,就压栈,
2.若是操作符,就连续弹出两个操作数,根据操作符计算两个操作数,最后把计算结果再次压到栈顶,
3.栈顶的值即为计算最终结果
注:先弹出的是第一操作数,后弹出的是第二操作数
'''

'''逆波兰表达式求值,参数是列表存储的表达式'''
def calcRevPolishNotation(numList = []):
    zhan = []
    i = 0
    while i < len(numList):
        re = 0
        if(numList[i].isdigit()):
            zhan.append(numList[i])        # 执行第1步
        else:
            a = float(zhan.pop())          # 执行第2步
            b = float(zhan.pop())
            if(numList[i] == '+'):
                re = b + a
            elif(numList[i] == '-'):
                re = b - a
            elif (numList[i] == '*'):
                re = b * a
            elif (numList[i] == '/'):
                re = b / a
            zhan.append(str(re))
        i += 1
    return zhan.pop()                      # 执行第3步

'''中缀表达式转后缀表达式步骤
1.遇到操作数:添加到后缀表达式中或直接输出
2.栈空时:遇到运算符,直接入栈
3.遇到左括号:将其入栈
4.遇到右括号:执行出栈操作,输出到后缀表达式,直到弹出的是左括号(注意:左括号不输出到后缀表达式)
5.遇到其他运算符:弹出所有优先级大于或等于该运算符的栈顶元素,然后将该运算符入栈
6.将栈中剩余内容依次弹出后缀表达式
'''

'''中缀表达式字符串转换为列表'''
def zhongToList(str = ''):
    i = 0
    numStr = ''
    flag = False
    numList = []
    while i < len(str):
        if(str[i].isdigit()):
            numStr += str[i]
            flag = True
        else:
            if(flag):
                numList.append(numStr)
                numStr = ''
                flag = False
            numList.append(str[i])
        i += 1
    if(flag):
        numList.append(numStr)
    return numList

'''中缀表达式转后缀表达式,所有表达式都是列表存储的'''
def listToHou(numList = []):
    level = {'(':0, '+':1, '-':1, '*':2, '/':2}
    stack = []
    RevPolishNotation = []
    i = 0
    while i < len(numList):
        if(numList[i].isdigit()):
            RevPolishNotation.append(numList[i])        # 执行第1步
        else:
            if(len(stack) == 0 or numList[i] == '('):
                stack.append(numList[i])                # 执行第2,3步
            elif(numList[i] == ')'):
                while True:                             # 执行第4步
                    out = stack.pop()
                    if(out != '('):
                        RevPolishNotation.append(out)
                    else:
                        break
            else:
                while True:                             # 执行第5步
                    if(len(stack) != 0 and level[stack[-1]] >= level[numList[i]]):
                        out = stack.pop()
                        RevPolishNotation.append(out)
                    else:
                        stack.append(numList[i])
                        break
        i += 1
    while True:                                         # 执行第六步
        if(len(stack) != 0):
            out = stack.pop()
            RevPolishNotation.append(out)
        else:
            break
    return RevPolishNotation

'''中缀表达式求值'''
def calc(str = ''):
    return calcRevPolishNotation(listToHou(zhongToList(str)))

if __name__ == "__main__":
    print(calc(sys.argv[1]))
    
'''示例表达式
12+(23+34*45-10)/2=783.5
34-12*(4+100)/(2+3)-4*(5-1)+100=-131.6
'''
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值