我需要編寫一個函數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