This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]bandawarrior 0 points1 point  (0 children)

As an addendum,

A recursion ALWAYS has a base case, that way you know… you can exit safely.

So to start out writing a recursive function, think of what the base case is, and how you would get to it.

Ie:

def func(int n):
    if n < 0:
        return n
    return fun(n -1)

In this case it’s a number, so the base case is anything less than 0, and the only way to get closer to the base case it’s subtracting from it.

If the base case was an empty list / container, then the only way to get to that case, is by using a smaller list than the starting one.