python 四则运算匹配

面完华为后满血复活的小黄鸭上线啦!

思想:

1、定义2个栈,一个压入数据,一个压入运算符

2、定义优先级别:

    priority={'(':1,'+':3,'-':3,'*':5,'/':5}

3、如果str[i]是数字,继续查看str[i+1]

        if str[i].isdigit():
            # print('1')
            start=i
            while i+1<len(str) and str[i+1].isdigit():
                i+=1
            date.append(int(str[start:i+1]))

4、如果元算符栈为空,或者str[i]=='(':

直接把元算符压入栈

5、如果str[i]==')'时:

就要把括号里表达式进行计算

运算符栈出栈一个运算符

数据栈出栈两个数据,把计算的结果再放入数据栈

6、如果st[i] in '+-*/':

运算符栈[-1]的优先级>str[i]的优先级,先进行计算

否则str[i]进栈

7、最后的结果:数据栈只剩一个元素,就是这样

def process(ope,date):
    '''数据栈出栈2个数据,符号栈出栈一个元素'''
    operator=ope.pop()
    b=date.pop()
    a=date.pop()
    if operator=='+':
        c=a+b
    elif operator=='-':
        c=a-b
    elif operator=='*':
        c=a*b
    else:
        c=a/b
    return c
def infix_cal(str):
    ope=[]  #符号栈
    date=[]  #运算符栈
    priority={'(':1,'+':3,'-':3,'*':5,'/':5}   #定义优先级别
    i=0
    while i<len(str):
        if str[i].isdigit():
            # 如果是数字
            start=i
            while i+1<len(str) and str[i+1].isdigit():
                i+=1
            date.append(int(str[start:i+1]))
            i+=1
        elif ope==[] or str[i]=='(':
            # 如果运算符栈空,或者运算符是'('
            ope.append(str[i])
            i+=1
        elif str[i]==')':
            # 运算符是')',对一对括号里面的数据进行计算
            while ope and ope[-1]!='(':
                tmp=process(ope,date)
                date.append(tmp)
            if ope==[]:
                raise SyntaxError('missing (')
            ope.pop()
            i+=1
        else:
            # str[i] in ‘+-*/’
            # 如果符号栈中是“*/”,就先进行计算
            while ope and priority[ope[-1]]>priority[str[i]]:
                tmp=process(ope,date)
                date.append(tmp)

            ope.append(str[i])
            i+=1

    while ope:
        if ope[-1]=='(':
            raise SyntaxError('extra (')
        tmp=process(ope,date)
        date.append(tmp)

    if len(date)==1:
        return date[0]
    else:
        print('error')

if __name__=='__main__':
    while True:
        try:
            line=input('inopt suffix evaluator :')
            if line=='end':
                break
            re=infix_cal(line)
            print(re)
        except Exception as e:
            print('Error:',type(e),e.args)










猜你喜欢

转载自blog.csdn.net/xiaolangmin/article/details/89362702
今日推荐