我正在尝试(使用运算符)计算最里面的列表,然后计算第二个最里面的列表,以此类推,直到没有更多列表为止。我也在尝试这样做,以便无论其中有多少嵌套列表,它都应该能够计算列表。
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。但是我只设法计算了最里面的列表,然后点击了返回操作符(operand1,operand2)来结束函数。
因此,我被困的是递归,因为无论何时计算出最内层列表,我似乎都无法弄清楚如何继续前进。
答案 0 :(得分:1)
以下递归函数应能完成工作:
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个元素是操作数而第一个元素是运算符来工作。我们递归计算子表达式,然后应用该操作。另外,如果我们的函数在任何时候接收到长度不等于3的列表,我们都将抛出该列表,因为它不能是格式正确的表达式。