Rocket has a loop that prints every star in the catalog. Raven dares him to rewrite it with recursion.
"Easy!" Rocket says. Then he stares at the screen. "Um, where do I start?"
Raven smiles. "What do you notice about the loop? When does it stop, and what changes each pass?"
"It stops when there are no stars left," Rocket says. "Each pass handles one star."
Nova blinks. "Here is a hint. Those two answers are your base case and your smaller step."
def show_all_loop(items):
for item in items:
print(item)
def show_all(items):
if items == []:
return
print(items[0])
show_all(items[1:])
show_all_loop(["Ember", "Frost"])
show_all(["Ember", "Frost"]) Output: Ember Frost Ember Frost
| Question | Answer for show_all |
|---|---|
| When does it stop? | When the list is empty: items == [] |
| What gets smaller? | The list loses its first item: items[1:] |
| Work in one pass? | print(items[0]) |
def shout_loop(words):
for w in words:
print(w + "!")
def shout(words):
if words == []:
return
print(words[0] + "!")
shout(words[1:])
shout(["go", "now"]) | Statement | True or false? |
|---|---|
| shout_loop and shout print the same lines. | ? |
| shout_loop has a base case. | ? |
| In shout, the base case is checked before the print. | ? |
| words[0] is the first word in the list. | ? |
You converted a loop like a pro! Tomorrow we go the other way and turn recursion into a loop.