Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 自下而上计算列表_Python_List_Recursion - Fatal编程技术网

Python 自下而上计算列表

Python 自下而上计算列表,python,list,recursion,Python,List,Recursion,我正在尝试计算(使用操作符)最里面的列表,然后是第二个最里面的列表等,直到没有更多的列表。我也在尝试这样做,这样无论列表中有多少嵌套列表,它都应该能够计算列表 import operator lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3'] dictionary = {'x1': 4, 'x2': 5, 'x3': 7} operator_dictionary = {"+": operator.add, "-": operator.sub, "

我正在尝试计算(使用操作符)最里面的列表,然后是第二个最里面的列表等,直到没有更多的列表。我也在尝试这样做,这样无论列表中有多少嵌套列表,它都应该能够计算列表

import operator

lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*": 
operator.mul, "/": operator.truediv}

def BINARYEXPR(program, dictionary):
    for i in range(len(program)):
        if isinstance(program[i],list):
            return BINARYEXPR(program[i],dictionary)

    operator = operator_dictionary[program[1]]
    operand1 = dictionary[program[0]]
    print("operand1: ", operand1)
    operand2 = dictionary[program[2]]
    print("operand2: ", operand2)

    return operator(operand1,operand2)

print (BINARYEXPR(lst,dictionary))
所以我想在这里首先计算x2*x3(5*7),它应该给我们35,然后计算x1*35(4*35),它应该给我们140,最后取140-x3(140-7),它应该返回133。但是我只计算了最里面的列表,并点击了结束函数的返回运算符(操作数1,操作数2)


因此,我一直停留在递归上,因为我似乎不知道如何在计算了第二个最里面的列表后,再转到第二个最里面的列表

下面的递归函数应该可以完成这项工作:

import operator


lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
                       operator.mul, "/": operator.truediv}


def calc(lst):
    if type(lst) == str:
        return dictionary[lst]

    if len(lst) != 3:
        raise ValueError("Incorrect expression: {}".format(lst))

    op = operator_dictionary[lst[1]]
    return op(calc(lst[0]), calc(lst[2]))

由于使用中缀符号,每个表达式都有三个组件:表达式、运算符、表达式。该函数的工作原理是假设第0和第2个元素是操作数,第1个元素是运算符。我们递归地计算子表达式,然后应用该操作。此外,如果函数在任何时候收到长度不同于3的列表,我们将抛出,因为这不是一个格式良好的表达式。

我不认为给用户一个完全不同的解决方案是对他们问题的适当回答。@ritlew完全不同的回答是什么意思?这个与最初编写的OP之间唯一的主要区别是,他们忘记了我提供的对函数的递归调用。您没有修复用户代码,而是提供了自己的代码来完成用户试图为自己编写代码的相同任务。你的代码看起来一点也不像OP。