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

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

#栈的结点
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)

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
递归实现表达式运算需要考虑一个算术表达式的各个元素以及运算符的优先级。下面是一个用C语言实现加减乘除模取模的递归解法的示例代码: ```c #include <stdio.h> int calculate(char *exp, int start); int parseNumber(char *exp, int *start) { int num = 0; while (exp[*start] >= '0' && exp[*start] <= '9') { num = num * 10 + (exp[*start] - '0'); (*start)++; } return num; } int calculate(char *exp, int start) { int num1 = parseNumber(exp, &start); while (exp[start] != '\0' && exp[start] != ')') { char op = exp[start++]; int num2 = parseNumber(exp, &start); switch (op) { case '+': num1 += num2; break; case '-': num1 -= num2; break; case '*': num1 *= num2; break; case '/': num1 /= num2; break; case '%': num1 %= num2; break; default: printf("Invalid operator\n"); return -1; } } return num1; } int main() { char expression[100]; printf("请输入要计算的表达式:"); scanf("%s", expression); int result = calculate(expression, 0); printf("计算结果为:%d\n", result); return 0; } ``` 以上代码中,函数`parseNumber`用于解析一个数值。函数`calculate`用于递归计算表达式,包括优先级高的乘除取模和优先级低的加减。在主函数中,用户输入一个表达式,然后调用`calculate`函数进行计算,并输出结果。 这个递归实现表达式运算的方法可以解析加减乘除取模运算,并且支持嵌套括号。但需要注意的是,这个实现有一些限制,例如不支持负数和浮点数的运算。如果需要更复杂的功能,可能需要更复杂的实现

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值