The station has 120 units of fuel for launch day. Rocket has the ready launches, but nobody knows yet if there is enough fuel for all of them.
"I wrote a total function in week ten," Rocket remembers. Raven asks, "What do you notice about our records? Each one already carries its fuel."
Nova shows the number 120 glowing above the fuel tanks. "Would you like a hint? Total the fuel, then compare it to the budget."
def total_fuel(launches):
total = 0
for launch in launches:
total = total + launch["fuel"]
return total
ready = [
{"name": "Moon hop", "fuel": 30},
{"name": "Ring tour", "fuel": 25},
{"name": "Comet chase", "fuel": 40},
]
budget = 120
need = total_fuel(ready)
print("Fuel:", need, "of", budget)
if need <= budget:
print("Cleared, with", budget - need, "to spare")
else:
print("Over budget by", need - budget) | The screen shows |
|---|
| Fuel: 95 of 120 |
| Cleared, with 25 to spare |
This test uses short records with only a name and fuel. The function only reads the fuel key, so the test is fair.
| Test | Does the program say Cleared? |
|---|---|
| budget = 95 | ? |
| budget = 94 | ? |
| budget = 200 | ? |
def total_fuel(launches):
total = 0
for launch in launches:
total = total + launch["fuel"]
return total
def spare(launches, budget):
return budget - total_fuel(launches)
plan = [{"name": "Probe", "fuel": 20}, {"name": "Scout", "fuel": 35}]
print(total_fuel(plan))
print(spare(plan, 100))
print(spare(plan, 55)) | budget | Is the plan of 55 cleared? (need <= budget) |
|---|---|
| 55 | ? |
| 54 | ? |
| 100 | ? |
| 20 | ? |
The budget check works! Tomorrow you will hunt the comms-log bugs.