Recursion guides/tricks?

Anyone have a guides/tricks/videos to solve recursion problems? I just can’t figure out how to solve these monsters

Posted Oct 16, 2020, 2:49 AM UTC

15
MmmVomit•

You need to be able to identify two basic things to write a recursive algorithm.

First, you need to identify the smallest, simplest version of your problem. So small and simple, you just write down what the answer is. This is your base case.

Second, you need to identify how to split your problem up so that you end up with a smaller version of itself. Then, you need to be able to express your problem in terms of this smaller version of itself. This is your recursive case.

Factorial is a very common example. We can define factorial(n) as n * n-1 * ... * 3 * 2 * 1. That would be pretty easy to write an iterative algorithm for. But can we identify the parts necessary for a recursive algorithm?

What's the base case? What's the smallest simplest case? Usually this is something like "empty list" or "1" or "0". In this case, factorial(1) is just 1.

What about the recursive case? Well, if we have n * n-1 * ..., what happens if we split the n off of it? We're left with n-1 * n-2 * .... That's just factorial(n - 1), which is a smaller version of the problem. To calculate factorial(n) we just do n * factorial(n - 1).

Once we have these pieces, the recipe is fairly simple. Put the base case right up top in an if statement. Then, to write the recursive case, just think about the "last step". Why does this work? Why don't we need to think about all the "middle" steps? Because each "middle" step is just the "last step" of a smaller problem.

def factorial(n):
    if n == 1:
        return 1

    return n * factorial(n - 1)

Is there a problem you're having trouble with? Post it here and see if you can identify the building blocks.

3
POGtastic•

Practice. It took practice to learn how to do a for and a while loop, too.

The best way that I've encountered is to download a Scheme compiler and start rolling your own versions of the typical functions that belong in the standard library. The Haskell Prelude is a great place for inspiration.

Once you do it with recursion, do it again with folds.

2
siemenology•

The way I think about problems that I solve recursively is to ask myself if I can break the problem up into a slightly simpler problem, whose solution I can use to easily find the answer. For example, what is factorial(5)? I know it's 5*4*3*2*1. But I can also think about it as finding factorial(4) and then multiplying by 5. Here factorial(4) is the slightly smaller problem, and multiplying it by 5 is how I take the solution to the smaller problem and convert it into an answer.

Once I have that worked out, I need to figure out how to solve the slightly smaller problem. If you do the above part correctly, then each application should result in a problem that is smaller than the last. Eventually it will reduce to a "simplest" case, or base case, and that case you need to program directly.

Say I want to find the length of the shortest path from one node in an unweighted graph to another. Let's say I know the length of the shortest path from each of my node's neighbors to the destination. Then the problem becomes very easy -- the shortest path from me to the destination is going to be one longer than the shortest path of any of my neighbors. In python, something like this:

def shortest_path(node, dest):
    shortest_paths = [shortest_path(neighbor, dest) for neighbor in node.neighbors]
    return 1 + min(shortest_paths)

Now, an immediate problem here is that when you ask your neighbor for the shortest path, they will immediately ask you for the shortest path (since they will ask all of their neighbors for the shortest path). We can solve that issue by passing around a list of nodes that have already been checked. We also need to handle the case where a node has no neighbors that haven't already been checked. We can do that by returning a negative value when that is the case, and filtering those out.

def shortest_path(node, dest, exclude = []):
    shortest_paths = [shortest_path(neighbor, dest, exclude + [node]) for neighbor in node.neighbors if neighbor not in exclude]
    shortest_paths = [path for path in shortest_paths if path >= 0]
    if len(shortest_paths) == 0:
        return -1
    return 1 + min(shortest_paths)

With that taken care of, we need to figure out the simplest possible case. The simplest case is the case where the node is already the destination! This is pretty easy to add:

def shortest_path(node, dest, exclude = []):
    if node == dest:
        return 0
    shortest_paths = [shortest_path(neighbor, dest, exclude + [node]) for neighbor in node.neighbors if neighbor not in exclude]
    shortest_paths = [path for path in shortest_paths if path >= 0]
    if len(shortest_paths) == 0:
        return -1
    return 1 + min(shortest_paths)

And we have a recursive solution.

2
AutoModeratorMOD•

To all following commenters: please, do not bring up the old circlejerk jokes/memes about recursion ("Understanding recursion...", "This is recursion...", etc.). We've all heard them n+2 too many times.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1
soflogator•

I think learning how to solve a factorial using recursion is a classic and useful example to help make sense of it. Most people have encountered factorials in math class so they are at least familiar enough with what's going on conceptually.

Just find out how to write a program that solves for a factorial in your language-of-choice. That's a good start.

1