zoukankan      html  css  js  c++  java
  • 递归--逆波兰表达式

    用递归解决递归形式的问题
    例题:逆波兰表达式
    逆波兰表达式是一种把运算符前置的算术表达式(其实一般教科书上称这种表达式为波兰表达式) ,例如普通的表达式2 + 3的逆波兰表示法为+ 2 3。逆波兰表达式的优点是运算符之间不必有优先级关系,也不必用括号改变运算次序,例如(2 + 3) * 4的逆波兰表示法为* + 2 3 4。本题求解逆波兰表达式的值,其中运算符包括+ - * /四个。

    输入:输入为一行,其中运算符和运算数之间都用空格分隔,运算数是浮点数

    输出:输出为一行,表达式的值。

    简单来说,这种表达式就是运算符号在全部在前面,需要运算的数值在后面,好像这种叫法是后缀表达式。
    运算的原理是:从左往右走,如果某个运算符后面是连着2个数字的,那么计算其结果,然后再把其结果放在运算符的位置,参与运算的数移除,后面剩余的数字再往左移,依次类推,完成整个表达式的计算。

    用递归解决递归形式的问题
    样例输入
    * + 11.0 12.0 + 24.0 35.0
    样例输出
    1357.000000
    提示:(11.0+12.0)*(24.0+35.0)

    python思想用了2种办法,第一种是利用栈的思想,一种是递归的思想。

    """
    第一种解法,list列表从后往前读入数据
    当数据是数字则加入栈,如果是运算符,则取出栈顶的前2个数字进行计算
    然后再把计算结果存入栈顶,
    后续依次规则进行,最后求出结果
    
    def Exp(list):
        stackList = []
        for i in reversed(list):
            if (i == "+"):
               num = len(stackList)
               newValue = float(stackList[num-1]) + float(stackList[num-2])
               stackList.pop()
               stackList.pop()
               stackList.append(newValue)
            elif (i == "-"):
                num = len(stackList)
                newValue = float(stackList[num - 2]) - float(stackList[num - 1])
                stackList.pop()
                stackList.pop()
                stackList.append(newValue)
            elif (i == "*"):
                num = len(stackList)
                newValue = float(stackList[num-1]) * float(stackList[num-2])
                stackList.pop()
                stackList.pop()
                stackList.append(newValue)
            elif (i == "/"):
                num = len(stackList)
                newValue = float(stackList[num - 2]) / float(stackList[num - 1])
                del stackList[-1]
                del stackList[-1]
                stackList.append(newValue)
            else:
                stackList.append(i)
        print(stackList[0])
    
    
    def main():
        print("请输入需要求解的波兰表达式(前缀):",end="")
        calculateList = []
        calculateList = input().strip().split(" ")
        Exp(calculateList)
    """
    #第二种解法:利用函数递归调用实现
    
    calculateList = []
    #逐位遍历list列表,每次读入1个字符
    pos = -1
    def Exp():
        global pos
        pos = pos +1
        chr = calculateList[pos]
        if (chr == "+"):
            return Exp() + Exp()
        elif (chr == "-"):
            return Exp() - Exp()
        elif (chr == "*"):
            return Exp() * Exp()
        elif (chr == "/"):
            return Exp() / Exp()
        else:
            return float(chr)
    def main():
        print("请输入需要求解的波兰表达式(前缀):", end="")
        global calculateList
        calculateList = input().strip().split(" ")
        result = Exp()
        print("计算结果为:%f"%result)
    
    if __name__ == "__main__":
        main()
  • 相关阅读:
    一个list<Map>里map其中的一个字段的值相同,如何判断这个字段相同,就把这个map的其他字段存入另一个map中
    ES6---箭头函数()=>{} 与function的区别
    VSCode代码格式化快捷键及保存时自动格式化
    NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException
    响应数据中文乱码
    tomcat将静态资源写入到浏览器乱码问题
    mark一款全局搜索工具,可以搜索文本内容
    mpvue 开发微信小程序搭建项目
    h5返回上一页ios页面不刷新
    微信小程序去除页面滚动条
  • 原文地址:https://www.cnblogs.com/an-wl/p/12345510.html
Copyright © 2011-2022 走看看