2016-05-06 63 views
-1

我需要编写一个函数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)函数。

有人可以给我一个线索怎么办? 谢谢。

+0

你必须使用mult2函数吗? –

+0

你试图解决的实际问题是什么? – Daenyth

+0

@Ni。是的,我必须使用它。 – Netta

回答

2

我不知道的是,例如调用正确的:

nestedSum(mult2([1,['a',3,'b',2],[4,['h',8,[10]]], -5])) 

调用列表上mult2()总会回报None。通过NonenestedSum()将始终导致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 
+0

非常感谢!你能告诉我“如果L”是什么意思吗?你为什么使用它? – Netta

+1

@Netta:'如果L:'?本来应该防止“None”被传入(就像在原始调用中那样),但它可以被删除。我已经更新了解决方案。 – mhawke

2

这将是更好的递归划分为不同的功能,只有确实像在以下几点:

sum(x for x in iflatten(L) if cond) 

其中iflatten是一个迭代器返回的扁平化的功能和版本cond你的情况type(x) == int and x % 2 == 0

def iflatten(L): 
    for i in L: 
     if isinstance(i, list): 
      for r in iflatten(i): 
       yield r 
     else: 
      yield i 

的代码测试出来是这样的:

L = [1,['a',3,'b',2],[4,['h',8,[10]]], -5] 

def iflatten(L): 
    for i in L: 
     if isinstance(i, list): 
      for r in iflatten(i): 
       yield r 
     else: 
      yield i 

sum(x for x in iflatten(L) if type(x) == int and x % 2 == 0) 

结果24

正如你不能改变

def mult2(n): 
    if type(n) == int and n%2 ==0: 
     return n 

我们可以在条件改变从type(x) == int and x % 2 == 0mult2(x) is not None所有功能,在其末端有一个隐含的return None

让测试过:

L = [1,['a',3,'b',2],[4,['h',8,[10]]], -5] 

def iflatten(L): 
    for i in L: 
     if isinstance(i, list): 
      for r in iflatten(i): 
       yield r 
     else: 
      yield i 

def mult2(n): 
    if type(n) == int and n%2 ==0: 
     return n 

sum(x for x in iflatten(L) if mult2(x) is not None) 

也导致24

0

如果可以的话不使用mult2,但仍然必须使用递归,这将做这项工作:

def sumArr(arr): 
    return sum([numVal(item) for item in arr]) 

def numVal(item): 
    if instanceof(item, int): return item 
    elif instance(item, list): return sumArr(item) 
    else: return 0 

sumArr([1,['a',3,'b',2],[4,['h',8,[10]]], -5]) # >>> 23