-1

Hello i am having trouble doing this problem it asks me to Write a recursive function that adds all the numbers in a deeply nested list which is made up numbers and words.

I have tried it but have gotten no where.

4 Answers4

3

I would start with a "filter" function yielding just the numbers: using Py 3.4 or better, that might be

import numbers
def getnumbers(alist, number_class=numbers.Number):
    for x in alist:
        if isinstance(x, number_class):
            yield x
        elif isinstance(x, list):
            yield from getnumbers(x)

(easy to translate to older versions if needed, just less elegant:-).

Then,

sum(getnumbers(alist))

will do the job.

I think this "factoring out" the pick of all numbers and nothing but numbers from a deeply nested list of numbers and words, vs summing them, makes for much more elegant and reusable code than trying to squash both tasks into a single function.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • what is the yield used for ? – jesus caballero Mar 23 '15 at 03:59
  • @jesuscaballero, `yield` produces an item then continues from the same place as the caller asks for another (by looping), while `return` would finish off the function's execution. `sum` implicitly loops, so gets all items. Functions using `yield` are known as **generators**. – Alex Martelli Mar 23 '15 at 13:44
3
def nested_sum(q):
    sum = 0
    for v in q:
        if type(v) == int or type(v) == float:
            sum += v
        elif type(v) == list:
            sum += nested_sum(v)
    return sum
Saksham Varma
  • 2,122
  • 13
  • 15
chw21
  • 7,970
  • 1
  • 16
  • 31
1
total = 0

def flat_sum(q):
    global total
    if not q:
        return
    if isinstance(q, list):
        if not isinstance(q[0], list) and not isinstance(q[0], str):
            total += q[0]
        else:
            flat_sum(q[0])
        flat_sum(q[1:])
    else:
        if not isinstance(q, str):
            total += q

flat_sum([1,"b",[4.7, 'a', -1, 99, ['hi', [7, 0]]]])
print total
Saksham Varma
  • 2,122
  • 13
  • 15
1

You can use numbers.Number to check for any number type.

from numbers import Number

def flat_sum(lst):
    if len(lst) == 0:
        return 0

    hd, tl = lst[0], lst[1:]

    if isinstance(hd, list):
        return flat_sum(hd) + flat_sum(tl)
    elif isinstance(hd, Number):
        return hd + flat_sum(tl)
    else:
        return flat_sum(tl)
axblount
  • 2,639
  • 23
  • 27