我需要编写一个函数nested_sum(L),它将对一个列表中的所有int求和,无论它们是否在另一个列表中。这与对另一个函数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
不幸的是,我无法更改mult2(n)函数的代码。我只能更改nested_sum(L)函数。
有人可以给我一个提示怎么办吗?谢谢你。
我不确定示例调用是否正确:
nestedSum(mult2( [1,['a',3,'b',2],[4,['h',8,[10]]], -5]))
调用mult2()
列表将始终返回None
。传递None
到nestedSum()
总是会导致TypeError
。
mult2()
用于过滤非整数和奇数整数。我认为您应该mult2
作为过滤器函数传递给nestedSum()
:
def mult2(n):
if type(n) == int and n%2 ==0:
return n
def nested_sum(L, predicate):
total = 0
for item in L:
if isinstance(item, list):
total += nested_sum(item, predicate)
elif predicate(item):
total += item
return total
现在调用该函数,将其mult2()
作为谓词函数传递给nested_sum():
>>> nested_sum([1,['a',3,'b',2],[4,['h',8,[10]]], -5], mult2)
24
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句