Chapter 20 - Python Quest
Dynamic Programming Workshop
Solve smaller states once, save their answers, and reuse them for routes, costs, and combinations.
Firefly Signal Notebook
A firefly team sends one signal in rounds 0 and 1. Every later round combines the signal counts from the previous two rounds, and the team wants the entire notebook so it can inspect every saved answer.
Write signal_notebook(rounds) so it returns a list of saved signal counts from round 0 through rounds. Round 0 is 1, round 1 is 1, and every later value is the sum of the previous two saved values. rounds is a nonnegative integer.
Interactive trace
Build every route count through step 6
Bottom-up DP starts with the smallest finished answers, then fills one new notebook cell at a time.
- ?0
- ?1
- ?2
- ?3
- ?4
- ?5
- ?6
Start with complete base states, then move left to right.
- goal
- 6
- writing
- -
- writes
- 0
- states solved
- 0
def hop_table(steps): dp = [0] * (steps + 1) dp[0] = 1 if steps >= 1: dp[1] = 1 for step in range(2, steps + 1): dp[step] = dp[step - 1] + dp[step - 2] return dpSample checks
signal_notebook(rounds=0)returns[1]Explanation: the notebook includes round zero itself, whose one empty starting signal is already a complete base answer, so the returned list has one cell
signal_notebook(rounds=1)returns[1,1]Explanation: rounds zero and one are both base states with one signal each, producing the two saved entries 1 and 1 without a recurrence step
Hint
Hints are ready when you want one.
Lesson reference
Review: Fill a table from complete smaller answers
Your Python
signal_notebook
Judge
Ready
Run your code when it feels ready.
