简体   繁体   中英

Summing elements inside tuple of tuples with recursion

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 (eg by raising TypeError ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM