• 0

[Python] Help with recursion function!


Question

Hello everyone,

I am learning recursion algorithms in this book I'm reading and one of the exercises is to make a recursion function that takes as input an integer, a list, string etc and if a list, it adds up all the integers in that list, skipping floats or strings: i.e. sum_ints([3, 3, 'a', 6]) = 12 but I wanted to step it up a notch and give it nested lists to deal with i.e. sum_ints([[[3]], [3, 4], 'a', 6]) = 16 and I cannot get the code to deal with nested lists. Would anyone please give me some hints as to how to code this in? Here is the code I have thus far:

# Developed by: ManOfMystery

'''Creates a recursion function that takes as input an integer, a list, string
etc and if a list, it adds up all the integers in that list, skipping floats 
or strings: i.e. sum_ints([[[3]], [3, 4], 'a', 6]) = 16'''

def sum_ints(x):

    # If x is an int, it returns x
    if isinstance(x, int):
        return x

    # If x is a string or float, it returns 0 
    elif isinstance(x, str) or isinstance(x, float):
        return 0

    # If it gets to end of list, stops the recursion
    elif x == []:
        return 0

    # Checks if x is list and looks at first element and decides whether it is 
    # a string, float or integer and deals with it
    elif isinstance(x, list):
        if isinstance(x[0], int):
            return x[0] + sum_ints(x[1:])
        else:
            return 0 + sum_ints(x[1:])

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

Simple:

def sum_ints(x):

    # If x is an int, it returns x
    if isinstance(x, int):
        return x

    # If x is a list, sum elements and return
    elif isinstance(x, list):
        sum = 0
        for elem in x:
            sum += sum_ints(elem)
        return sum

    # If x is neither, return 0
    else:
        return 0

:)

Link to comment
Share on other sites

  • 0

Thank you very much for replying! Unfortunately, the exercise states that no loops can be used, so it must be entirely recursed. I actually got it after thinking about it more deeply! I apologize for over-commenting but as I am still learning python, it helps if I write things down in plain English first.

Things I threw at it are as follows:

sum_ints(3) = 3

sum_ints('a') = 0

sum_ints('3') = 0

sum_ints(3.0) = 0

sum_ints([3]) = 3

sum_ints([]) = 0

sum_ints([[[[3]]]]) = 3

sum_ints([[2], 3, [[4, 5, 'a']]]) = 14

sum_ints({1: 2, 3: 4}) = 0

sum_ints((1, 2, 3, 4)) = 0

# Developed by: ManOfMystery

def sum_ints(x):
    '''Creates a recursion function that takes as input an integer, a list, 
    string etc and if a list, it adds up all the integers in that list, 
    skipping floats or strings: i.e. sum_ints([[[3]], [3, 4], 'a', 6]) = 16'''

    if isinstance(x, int):
        '''If x is an integere, return it'''

        return x

    elif x == []:
        '''When it gets to end of list, stop recursion'''

        return 0

    elif isinstance(x, list):
        '''If x is a list, deal with it accordingly'''

        if isinstance(x[0], int):
            '''If first element is an integer, store it and re-call the
            function with the elements after it'''

            return x[0] + sum_ints(x[1:])

        elif isinstance(x[0], list):
            '''If first element is a list, return it to recursion and re-call 
            the function with the elements after it'''

            return sum_ints(sum_ints(x[0])) + sum_ints(x[1:])

        else:
            '''Otherwise, store a zero and re-call the function with the rest
            of the elements'''

            return 0 + sum_ints(x[1:]) 
    else:
        '''Otherwise, return zero'''

        return 0

Link to comment
Share on other sites

  • 0

Congrats for figuring it out by yourself. I missed the "can't use a loop" part.

However, your function is very complicated for nothing. It can be reduced to just:

def sum_ints(x):

    if isinstance(x, int):        
        return x

    elif isinstance(x, list) and len(x) > 0:    
            return sum_ints(x[0]) + sum_ints(x[1:])

    return 0

This is precisely because of its recursive nature: you don't need to check for anything more than once since that is handled by recursion.

EDIT: fixed typos in code. Should run now.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.