Reputation: 100
I'm trying to return the sum of all elements on a set of tuples inside tuples, but the last value is always None
, so I get
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
using the code below.
How do I skip this last value?
It has to be done with recursion.
L = (1, (2, (3, None)))
def sum(L):
if not L:
return None
else:
return L[0] + sum(L[1])
Upvotes: 1
Views: 350
Reputation: 114440
If that is really the structure of your tuple, just return zero when you reach the end:
def my_sum(L):
if not L:
return 0
else:
return L[0] + my_sum(L[1])
And don't shadow the name of a built-in. It's bad practice, even if it's technically legal.
Also, I don't think this is necessarily a good candidate for recursion. An iterative solution works the same, and without creating a new stack frame for every level:
s = 0
while L:
s += L[0]
L = L[1]
That's just a personal bonus for when you can make the design decision.
Upvotes: 1
Reputation: 17408
In [117]: L = (1, (2, (3, None)))
...:
...: def sum(L):
...: if not L:
...: return 0
...: else:
...: return L[0] + sum(L[1])
...:
In [118]: sum(L)
Out[118]: 6
Upvotes: 1