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.
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.
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.
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
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
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)