Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: Chapter 10: Recursively Recurse with Recursion
Дальше: The Base Case

Recurse Instead of Loop

Let’s say you work at NASA and need to program a countdown function for launching spacecraft. The particular function that you’re asked to write should accept a number—such as 10—and display the numbers from 10 down to 0.

Take a moment and implement this function yourself. When you’re done, read on.

Odds are that you wrote a simple loop, along the lines of this implementation:

 def​ ​countdown​(number):
 while​ number >= 0:
 print​(number)
  number -= 1

Nothing is wrong with this implementation, but it may have never occurred to you that you don’t have to use a loop.

How?

Let’s try recursion instead. Here’s a first attempt at using recursion to implement our countdown function:

 def​ ​countdown​(number):
 print​(number)
 
  countdown(number - 1)

Let’s walk through this code step by step.

Step 1: We call countdown(10), so the argument variable number starts out as 10.

Step 2: We print number (which contains the value 10) to the console.

Step 3: Before the countdown function is complete, it calls countdown(9), since number - 1 is 9.

Step 4: countdown(9) begins running. In it, we print number (which is currently 9) to the console.

Step 5: Before countdown(9) is complete, it calls countdown(8).

Step 6: countdown(8) begins running. We print 8 to the console.

Before we continue stepping through the code, note how we’re using recursion to achieve our goal. We’re not using any loop constructs, but by simply having the countdown function call itself, we’re able to count down from 10 and print each number to the console.

In almost any case in which you can use a loop, you can also use recursion. Now, just because you can use recursion doesn’t mean that you should use recursion. Recursion is a tool that allows for writing elegant code. In the preceding example, the recursive approach isn’t necessarily any more beautiful or efficient than using a classic loop. However, we’ll soon encounter examples in which recursion shines. In the meantime, let’s continue exploring how recursion works.

Назад: Chapter 10: Recursively Recurse with Recursion
Дальше: The Base Case