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[0],int):
        return tup[0] + soma_els_atomicos(tup[1:])
    if isinstance(tup[0],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[0],tuple):
        return 0 + soma_els_atomicos(tup[1:])

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

    if isinstance(tup[0],tuple):
        return soma_els_atomicos(tup[0]) + 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).

Related
What is tail recursion?
What's the difference between lists and tuples?
How to remove an element from a list by index
Getting the last element of a list
How do I get the number of elements in a list?
Running unittest with typical test directory structure
What are “named tuples” in Python?
How to sort (list/tuple) of lists/tuples by the element at a given index?
Convert list to tuple in Python