python利用栈与递归实现能分辨优先级(+-*/)与括号的计算器

本文介绍了一种使用栈的数据结构来解析并计算包含四则运算(加、减、乘、除)及括号的数学表达式的方法。通过创建符号栈和数字栈,算法能够正确处理运算符的优先级,并通过递归解决括号内的计算问题,最终得到表达式的计算结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    前一篇文章中处理乘除法是利用往后多读一个符号,若为乘除号就计算出结果再继续往后读入;这里用栈实现,就是将读到的第一个符号压入符号栈,在读到下一个符号时,与栈顶的符号的优先级进行比较,若优先级比栈顶的那个符号低,就将栈顶符号的连接的两个数字(数字存在数字栈中)进行运算,否则将当前符号压入符号栈。遍历完一遍之后算式就只剩加减号了(或者直接得出答案了),然后就很简单了。至于括号的处理,和上一篇文章中的一样,在读入数字的时候,将括号内的内容视为整体用递归解决

#栈的结点
class Node(object):
    def __init__(self, datas):
        self.data = datas
        self.next = None

#栈
class Stack(object):
    def __init__(self):
        self.top = None

    def isEmpty(self):
        if self.top == None:
            return True
        else:
            return False

    def push(self, data):
        node = Node(data)
        node.next = self.top
        self.top = node
        return self

    def pop(self):
        if self.isEmpty():
            print("the stack is empty already")
            return
        else:
            popData = self.top.data
            self.top = self.top.next
            return popData

    #计算函数
    def cal(exp):
        #operator是符号栈
        #operand是运算数栈
        #loc是当前读取位置
        #count用来匹配括号与括回
        #operand1与operand2是两个运算数,存储operand中pop出的数字
        #op是运算符,存储operator中pop出的符号
        operator = Stack()
        operand = Stack()
        loc = 0
        count = 0
        while loc < len(exp):
            if isOperator(exp[loc]):
                if not operator.isEmpty():
                    while (not operator.isEmpty()) and priority(operator.top.data) >= priority(exp[loc]):
                        operand1 = operand.pop()
                        operand2 = operand.pop()
                        op = operator.pop()
                        operand.push(int(result(op, operand2, operand1)))
                operator.push(exp[loc])
            else:
                firstOp = exp[loc]
                if firstOp != "(":
                    firstOp = int(firstOp)
                #处理括号
                else:
                    locStart = loc + 1
                    count += 1  # 为了将( 与 ) 进行匹配
                    while count != 0:
                        loc += 1
                        if exp[loc] == "(":
                            count += 1
                        elif exp[loc] == ")":
                            count -= 1
                    locEnd = loc
                    firstOp = cal(exp[locStart:locEnd])
                operand.push(firstOp)
            loc += 1
        while not operator.isEmpty():
            operand1 = operand.pop()
            operand2 = operand.pop()
            op = operator.pop()
            operand.push(int(result(op, operand2, operand1)))
        evaluate = operand.pop()
        return evaluate
    return cal(x)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值