Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Python Recursion

I'm trying to write a recursive function but got stuck. A really long explanation would help.

times is the number of times to repeat and data is the number or string to be repeated e.g replicate_recur(3, 5) should return [5,5,5].

Here is my attempt.

def replicate_recur(times, data):
    """This is a recursive function
    that returns an array containing repetitions of the data argument"""
    if not isinstance(times, int):
        raise ValueError('Invalid argument')
    elif not isinstance(data, (int, str)):
        raise ValueError('Invalid argument')
    elif times <= 0:
        return []
        arr = []
        if len(arr) == times:  # base case
            return arr  # no recursive call
            return [(str(data) + ',') * times]

1 Answer

Steven Parker
Steven Parker
216,165 Points

Remember that a recursive function will call itself, but with one or more arguments modified. For example, a function to add all numbers from 1 to a specific end value might look like this:

def add_numbers(val):
    if val > 1:
        return val + add_numbers(val - 1)
    return 1

You should find that your function will require much less code once you structure it to just do a part of the task, and use itself to do the rest.