I'd be grateful if someone could tell me why sum_all([1,[2,[3,[4]]]]) doesn't work? It says that it can only concatenate list (not "int") to list but if my code works as I think it should that shouldn't happen. Btw my code uses recursion to sum all elements of a list regardless of whether they're an integer or another list
def rec_sum(numbers):
lnum = len(numbers)
if lnum == 0:
return 0
elif lnum == 1:
return numbers[0]
else:
numbers[0] = numbers[-1] + numbers[0]
del numbers[-1]
return rec_sum(numbers)
def sum_all(numbers):
lnum = len(numbers)
if lnum == 0:
return 0
elif lnum == 1:
if isinstance(numbers[0], int):
return numbers[0]
elif isinstance(numbers[0], list):
return rec_sum(numbers[0])
else:
if isinstance(numbers[-1], list) and isinstance(numbers[0], list):
numbers[0] = rec_sum(numbers[0]) + rec_sum(numbers[-1])
del numbers[-1]
return sum_all(numbers)
elif isinstance(numbers[-1], list) and isinstance(numbers[0], int):
numbers[0] = numbers[0] + rec_sum(numbers[-1])
del numbers[-1]
return sum_all(numbers)
elif isinstance(numbers[-1], int) and isinstance(numbers[0], list):
numbers[0] = rec_sum(numbers[0]) + numbers[-1]
del numbers[-1]
return sum_all(numbers)
elif isinstance(numbers[-1], int) and isinstance(numbers[0], int):
numbers[0] = numbers[0] + numbers[-1]
del numbers[-1]
return sum_all(numbers)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module> sum_all([1, [2, [3, [4]]]])
File "C:/Users/#/Documents/python/recursion.py", line 36, in sum_all numbers[0] = numbers[0] + rec_sum(numbers[-1])
File "C:/Users/#/Documents/python/recursion.py", line 17, in rec_sum numbers[0] = numbers[-1] + numbers[0]
TypeError: can only concatenate list (not "int") to list