Validate a cargo record
Cargo records arrive from several warehouses, typed by different people. Before an item goes on the manifest, it has to pass a check, and when it fails, the warehouse needs to know everything that is wrong with it, not just the first problem.
Write the check as a function that collects the problems, then add a rule for the ID format.
Finish stage 1 to unlock this stage.
Write validate_cargo(item), which returns a list of problems: one missing ... for each field in REQUIRED that the record doesn't have, in that order, and negative mass for a mass below 0. The loop at the bottom then prints:
CG-0042: OK CG-0043: missing item, negative mass CG-0044: missing mass_kg CG-42: OK
Start with problems = [], append each problem you find, and return problems at the end. Check that "mass_kg" is there before comparing it.
Finish stage 1 to unlock this stage.
Cargo IDs have a fixed format: CG- followed by exactly four digits. Add bad ID format to the problems when the ID doesn't match:
CG-0042: OK CG-0043: missing item, negative mass CG-0044: missing mass_kg CG-42: bad ID format
Check that the ID starts with "CG-", is 7 characters long, and that item["id"][3:].isdigit(). Only check an ID that is there.
Hints
Returning Dictionary or List
# Returning complex data structures from functions
def planet_data(name):
"""Returns dictionary with planet info."""
database = {
"Mars": {"diameter_km": 6779, "moons": 2, "type": "rocky"},
"Jupiter": {"diameter_km": 139820, "moons": 95, "type": "gas giant"},
"Saturn": {"diameter_km": 116460, "moons": 146, "type": "gas giant"}
}
return database.get(name, {"error": f"Planet {name} not found"})
def mission_checklist(crew_size, days):
"""Returns list of supply items scaled to crew and duration."""
water_liters = crew_size * days * 2.5
food_kg = crew_size * days * 1.8
oxygen_kg = crew_size * days * 0.84
return [
f"Water: {water_liters:.0f} liters",
f"Food: {food_kg:.0f} kg",
f"Oxygen: {oxygen_kg:.1f} kg"
]
mars = planet_data("Mars")
print(f"Mars has {mars['moons']} moons and is {mars['type']}")
pluto = planet_data("Pluto")
print(pluto)
supplies = mission_checklist(4, 180)
print("Mission supplies needed:")
for item in supplies:
print(f" - {item}")
Separate arguments with commas. They're passed on every Run as sys.argv[1:].