Python3实现逆波兰表达式计算

import  logging
logging.basicConfig(level=logging.INFO)
import re

##判断字符串是否为小数
def isnumber(num):
    regex = re.compile(r"^(-?\d+)(\.\d*)?$")
    if re.match(regex,num):
        return True
    else:
        return False

#自定义栈
class PyStack(object):

    def __init__(self,initSize=20,incSize=10):
        self.initSize=incSize
        self.incSize=incSize
        self.stackList=[]
        self.top=self.bottom=0

    def push(self,ele):
        if self.top-self.bottom>=self.initSize:
            self.incSize+=self.initSize
        self.stackList.append(ele)
        self.top+=1

    def pop(self):
        if self.top-self.bottom>0:
            self.top-=1
            ret=self.stackList.pop()
            return ret
        else:
            return None

    def len(self):
        return  self.top-self.bottom

##算式转化为中缀表达式列表
def equation2List():
    equation=input("请输入你要运算的方程:")
    result=[]
    buffNum=[]
    for i in equation:
        if i.isdigit() or i=='.':
            buffNum.append(i)
        else:
            if len(buffNum)>0:
                result.append("".join(buffNum))
                buffNum.clear()
            result.append(i)
    if len(buffNum)>0:
        result.append("".join(buffNum))
        buffNum.clear()
    logging.info(result)
    return result

##中缀表达式转后缀表达式
## 1+2*(3+4)=15
##1 2 3 4 + * +
def mid2EndSuffix(list):
    resultList=[]
    stack=PyStack()
    for i in list:
        if isnumber(i):
            resultList.append(i)
        elif ')' == i:
            while stack.len()>0:
                item=stack.pop()
                logging.debug(")pop==%s"%(item))
                if '('==item:
                    break
                else:
                    resultList.append(item)
        elif '+' == i or '-' == i:
            if stack.len() == 0:
                stack.push(i)
                logging.debug("+-None=push==%s"%i)
            else:
                while stack.len()>0:
                    item2=stack.pop()
                    logging.debug("+-=pop==%s"%item2)
                    if '(' == item2:
                        stack.push(item2)
                        logging.debug("+-=(push==%s"%item2)
                        break
                    else:
                        resultList.append(item2)
                stack.push(i)
                logging.debug("+-lastpush==%s"%i)
        elif '*' == i or '/' == i or '(' == i:
            stack.push(i)
            logging.debug("*/(push==%s"%i)
        else:
            print("输入格式有误")
    while stack.len()>0:
        item3=stack.pop()
        logging.debug("last==pop=%s"%item3)
        resultList.append(item3)
    return  resultList

##后缀表达式计算结果
def   calEndSuffixResult(list):
    stack=PyStack()
    sumEnd=0
    if len(list)==0:
        return sumEnd
    for i  in list:
        if isnumber(i):
            stack.push(float(i))
        elif '+'==i:
            a=stack.pop()
            b=stack.pop()
            stack.push(b+a)
        elif '-'==i:
            a = stack.pop()
            b = stack.pop()
            stack.push(b - a)
        elif '*'==i:
            a = stack.pop()
            b = stack.pop()
            stack.push(b * a)
        elif '/'==i:
            a = stack.pop()
            b = stack.pop()
            if a==0:
                print('%d/%d分子不能为0'%(b,a))
            else:
                stack.push(b/a)
    return stack.pop()

if __name__=='__main__':
    eList=equation2List()

    midEList=mid2EndSuffix(eList)
    logging.info(midEList)

    lastResult=calEndSuffixResult(midEList)
    print("算式的结果是:",lastResult)

目前程序还有个缺陷,控制台输入的数字一般是斜体,如果是直体会无法识别。
暂时不清楚为啥会出现直体的情况,如果有知道的同学可以解答下

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值