The fleet sends signals home through relay stations. Each station doubles the signal power.
Nova wrote a recursive function called boost. Rocket wants a loop version for the relay panel.
"A signal of 3 through 4 stations," Rocket says. "That is 3, then 6, then 12, then 24, then 48!"
Raven asks, "What do you notice about each station?"
"Every station does the same thing. It doubles," Rocket says. Nova hums. "Here is a hint. Same thing, many times. Sound familiar?"
def boost(power, stations):
if stations == 0:
return power
return boost(power * 2, stations - 1)
print(boost(3, 4)) Output: 48
Each call doubles the power and has one fewer station left. With no stations left, the power is returned as it is.
range(stations) makes the numbers 0 up to one less than stations. So the loop runs exactly stations times.
def boost_loop(power, stations):
for i in range(stations):
power = power * ____
return power
print(boost_loop(3, 4)) | Statement | True or false? |
|---|---|
| The base case stations == 0 matches the loop running out of turns. | ? |
| boost_loop calls boost_loop. | ? |
| boost(3, 4) and boost_loop(3, 4) return the same number. | ? |
def triple(n, times):
if times == 0:
return n
return triple(n * 3, times - 1)
def triple_loop(n, times):
for i in range(times):
n = n * 3
return n
print(triple(2, 3), triple_loop(2, 3)) | Statement | True or false? |
|---|---|
| triple and triple_loop always return the same number. | ? |
| triple_loop calls itself. | ? |
| times - 1 is the smaller step in triple. | ? |
| triple(2, 1) returns 5. | ? |
Excellent! You can now move between loops and recursion in both directions. Tomorrow we decide which one to pick.