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:
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)
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.
To download the code in this course, click the link below:
To download the slides in this course, click the link below: