← Back to course
Code Crew G4 / Week 12 / Wednesday
3/6
Week 12 Β· Launch day

Wednesday

Check the fuel budget
// Build the launch planner
⏱ about 15 min

Wednesday: Check the fuel budget

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."

Piece 3: total and compare

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.

The budget drops to 90. What is the first number on the last line?
What word does that last line start with?
TestDoes the program say Cleared?
budget = 95?
budget = 94?
budget = 200?
WHY THIS EXERCISETesting right at the edge, like 95 and 94, is where bugs hide.
Mars run is fixed and joins the ready list with 70 units. The budget is 120. How much over is the plan?
WHY THIS EXERCISEA planner lets the crew test choices before launch day.
Try it
Make up a budget and three trips on paper.
Total the trips and decide: cleared or over?

Practice lab: how much is spare?

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))
What does line 11 show?
What does line 12 show?
What does line 13 show?
SPARE CHECK
  • Read the question.
  • Tap your answer.
What does spare return when the plan uses exactly the budget?
Which function does spare call?
A third launch with 10 fuel joins the plan. What does total_fuel(plan) return?
budgetIs the plan of 55 cleared? (need <= budget)
55?
54?
100?
20?
WHY THIS EXERCISE55 and 54 test the edge. That is where off-by-one bugs live.
What does spare(plan, 70) return?
WHY THIS EXERCISEThe budget changes, and the function gives a new answer right away.

The budget check works! Tomorrow you will hunt the comms-log bugs.

← Tuesday