我需要编写一个函数nested_sum(L)它会将列表中的所有int整合到一个列表中,而不管它们是否在另一个列表中。这与recrusively调用另一个功能mult2(n)。复杂的递归函数
实施例:
>>> nestedSum(mult2([1,['a',3,'b',2],[4,['h',8,[10]]], -5]))
24
我试图实现代码:
def mult2(n):
if type(n) == int and n%2 ==0:
return n
def nested_sum(L):
total = 0
for i in L:
if isinstance(i, list):
total += nested_sum(i)
else:
total += i
return total
而且unfortanetly我不能改变MULT2(n)的函数的代码。我只能改变nested_sum(L)函数。
有人可以给我一个线索怎么办? 谢谢。
你必须使用mult2函数吗? –
你试图解决的实际问题是什么? – Daenyth
@Ni。是的,我必须使用它。 – Netta