# LaVOZs

The World’s Largest Online Community for Developers

'; python - Summing elements inside tuple of tuples with recursion - LavOzs.Com

So my problem is as follows:

I have a tuple with 1 or more tuples inside it and i want sum all the numbers inside the tuple. But something is missing because theres a case when u have a tuple with a tuple with elements inside, it doesnt even checks them.

For example:

``````def soma_els_atomicos(tup):
if tup == ():
return 0
if isinstance(tup,int):
return tup + soma_els_atomicos(tup[1:])
if isinstance(tup,tuple):
return 0 + soma_els_atomicos(tup[1:])
``````

Input:

``````>>>tup = (3, ((((((6, (7, ))), ), ), ), ), 2, 1)
``````

Output:

``````>>>soma_els_atomicos(tup)
>>> 6
``````

The output should be 19 but I can't seem to notice what's missing.

This part of your code has a logical error:

``````    if isinstance(tup,tuple):
return 0 + soma_els_atomicos(tup[1:])
``````

Supposing `tup` is a tuple, then the recursive sum should equal the sum of the numbers in `tup` plus the sum of the numbers in `tup[1:]`. Your code uses `0` instead of the sum of the numbers in `tup`. You can fix it this way:

``````    if isinstance(tup,tuple):
return soma_els_atomicos(tup) + soma_els_atomicos(tup[1:])
``````

Example:

``````>>> tup = (3, ((((((6, (7, ))), ), ), ), ), 2, 1)
>>> soma_els_atomicos(tup)
19
``````

By the way, I would recommend writing your code with `if`/`elif`/`elif` instead of separate `if` statements, and use an `else` case to handle invalid input types (e.g. by raising `TypeError`).