-1

I need to write a function nested_sum(L) that will sum all the ints inside a list no matter if they are inside another list. This with calling recrusively to another function mult2(n).

Example:

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

I tried to code this:

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

And unfortanetly I can't change the code of mult2(n) function. I can only change the nested_sum(L) function.

Can someone please give me a clue what to do? Thank you.

Anonymous
  • 11,740
  • 3
  • 40
  • 50
Netta
  • 63
  • 8
  • Must you use the mult2 function? – kmaork May 06 '16 at 13:00
  • What's the actual problem you're trying to solve? – Daenyth May 06 '16 at 13:01
  • @Ni. yes, I have to use that. – Netta May 06 '16 at 13:01
  • @Daenyth I can't code it correctly unfortanately – Netta May 06 '16 at 13:02
  • You still aren't saying what the problem is. What is the actual problem. What is the error? What behavior do you want to see and what do you actually see? – Daenyth May 06 '16 at 13:04
  • @Daenyth I'm trying to code the function nested_sum(L) that it will cal recrusively to the unchangeable function mult2(n). it will sum all the ints inside a list no matter if they are inside another list. – Netta May 06 '16 at 13:04
  • I don't understand. What do you want to achieve, what kind of use of mult2 you must implement, and why – kmaork May 06 '16 at 13:05
  • 1
    this can be of interest: [flatten-an-irregular-list-of-lists-in-python](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python) – Copperfield May 06 '16 at 13:28

3 Answers3

2

It would be better to separate out the recursion into a function that only does that like in the following:

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

where iflatten is an iterator returning version of the flatten function and cond is in your case 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

The code tests out like this:

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)

results in 24.

As you can't change

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

We can change the condition from type(x) == int and x % 2 == 0 to mult2(x) is not None as all functions have an implicit return None at their end.

Lets test that too:

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)

Also results in 24

Dan D.
  • 73,243
  • 15
  • 104
  • 123
2

I'm not sure that the example invocation correct:

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

Calling mult2() on a list will always return None. Passing None to nestedSum() will always cause a TypeError.

mult2() is designed to filter out non-integers and odd integers. I think that you are supposed to pass mult2 as a filter function to 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

Now to invoke the function, pass mult2() as the predicate function to nested_sum():

>>> nested_sum([1,['a',3,'b',2],[4,['h',8,[10]]], -5], mult2)
24
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Thank you so much!!! Can you just tell me what is the meaning of "if L"? why did you use that? – Netta May 06 '16 at 13:24
  • 1
    @Netta: `if L:`? Was supposed to guard against `None` being passed in ( as done in the original invocation), but it can be removed. I've updated the answer to remove it. – mhawke May 06 '16 at 13:36
0

If you can do it without using mult2 but still must use recursion, this would do the job:

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
kmaork
  • 5,722
  • 2
  • 23
  • 40