Thinking Recursively in Python: Overview

A lot of real-world problems can be broken down into smaller variations of themselves, so you can use recursion to solve them. You’ll see how you can use iteration and then recursion to help Santa Claus deliver presents.

Iterative solution

Santa Claus goes to each house, delivers the presents, and continues on to the next house:

Python
``````houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"]

def deliver_presents_iteratively():
for house in houses:
print("Delivering presents to", house)
``````
Copied!

Recursive solution

Santa Claus designates all the work to one elf. That elf follows these rules:

• If they are responsible for more than 1 house, then they are a manager and split their workload between two elves, who then follow these same rules.
• If the elf is responsible for only 1 house, then they are a worker and deliver the presents to that house.

You’ll go through the code for this solution in the third lesson in this course.

Sample Code (.zip)

1.0 KB