zoukankan      html  css  js  c++  java
  • 递归--四则运算表达式求值

    输入为四则运算表达式,仅由整数、+、-、*、/ 、(、)组成,没有空格,要求求其值。假设运算符结果都是整数。"/"结果也是整数

    解题思想:因为四则运算有优先级,所以在设计递归的时候,需要注意。这里设计为:表达式-项-因子-带括号表达式或整数,这里只是给了个名称上的定义,可以不用具体的纠结什么是项、什么是因子,这些名称你都可以自己定义。关键的是要好好理解,“+,-”的运算级别最低,“()”括号的运算级别最好,“乘除”居中,因此递归的调用也是参照这样来设计的。表达式可以是一个单独的项,也可以是2个项之间进行加、减,项可以是因子,或者多个因子乘除,因子是整数或者再是一个带括号的表达式。

    举个例子:2+3*4,读入2后,接着读入+符号,接下来是不能直接求2+3的,需要继续下一项,递归遍历,就是先计算3*4,运算是先返回3个一个整数,然后因子做*运算,接着继续递归调用,返回4是个整数,然后把3*4的结果返回给上一个递归调用的函数,把这个计算结果求出来后,再与2相加,这样就很好的解决了运算符优先级的问题。

    简单理解:

     Python代码实现:

    """
    输入:(2+3)*(5+7)+9/3
    输出: 63
    """
    #输入需要计算的表达式
    in_exp = ""
    #表达式的每个字符的位置
    pos = 0
    #计算表达式的值
    def Expression_value():
        global in_exp,pos
    
        #计算第一个表达式的值
        result = Term_value()
        more = True
        while more :
            pos = pos + 1
            #判断访问list是否越界
            if (pos >= len(in_exp)):
                more = False
                break
            op = in_exp[pos]
            if (op == "+" or op == "-"):
                pos = pos + 1
                value = Term_value()
                if (op == "+"):
                    result += value
                else:
                    result -= value
            else:
                more = False
    
        return result
    
    
    #计算项的值
    def Term_value():
        global in_exp,pos
        # 计算第一个表达式的值
        result = Factor_value()
        more = True
        while (more):
            pos = pos + 1
            # 判断访问list是否越界
            if (pos >= len(in_exp)):
                more = False
                break
            op = in_exp[pos]
            if (op == "*" or op == "/"):
                pos = pos + 1
                value = Factor_value()
                if (op == "*"):
                    result *= value
                else:
                    result /= value
            else:
                pos = pos - 1
                more = False
    
        return result
    
    #计算因子的值
    def Factor_value():
        global in_exp,pos
        result = 0
        c = in_exp[pos]
        if (c == "("):
            pos = pos + 1
            result = Expression_value()
        else:
            while (c.isdigit()):
                result = 10*result + int(c)
                pos = pos + 1
                #判断是否超过list的长度
                if (pos == len(in_exp)):
                    break
                c = in_exp[pos]
            pos = pos - 1
            #while (isdigit(c))
            #result = 10 * result + c - '0';
    #在ASCII编码中, 0~9 的编码是 0x30~0x39, 所以当c在‘0'~'9'的范围中时,c - '0' 就相当于计算c的实际数值,
    #
    例如 c 是 '1', 则 c - '0' = 1, 把字符值转为数字值1了 
    
    
        return result
    def main():
        global in_exp
        in_exp = input("请输入需要计算的表达式:")
        rtn = Expression_value()
        print("表达式: "+in_exp+"的运算结果为:%d" %rtn)
    
    
    if (__name__ == "__main__"):
        main()
  • 相关阅读:
    损失函数
    numpy中的broadcast
    混合模型
    贝叶斯学习
    python3中输出不换行
    C++11 实现 argsort
    Python中的闭包
    C语言 fread()与fwrite()函数说明与示例
    DFT与傅里叶变换的理解
    MISRA C:2012 Dir-1.1(只记录常犯的错误和常用的规则)Bit-fields inlineC99,NOT support in C90 #pragma
  • 原文地址:https://www.cnblogs.com/an-wl/p/12365586.html
Copyright © 2011-2022 走看看