Space Python Loading Python…

Mass by category

Write the codeMedium 2 stages

The load planners don't need every item: they need to know how much each kind of cargo weighs, because food, life support and spares go into different racks with different mass limits.

Total the manifest by category, then rank the categories by mass.

Add up the mass of each category in a dict called totals, then print each category with its total, in the order the categories first appear:

life support: 49.8 kg
spares: 2.4 kg
food: 67.0 kg
crew: 3.4 kg

Start with totals = {}. For each record, totals.get(category, 0) gives the total so far, or 0 for a category not seen yet; add the record's mass and store it back under the category.

Total by category
A dict of totals, any manifest

Finish stage 1 to unlock this stage.

Print the categories from heaviest to lightest, each with its share of the whole load, rounded to a whole percent:

food: 67.0 kg (55%)
life support: 49.8 kg (41%)
crew: 3.4 kg (3%)
spares: 2.4 kg (2%)

sorted(totals, key=totals.get, reverse=True) gives the categories ordered by their totals. sum(totals.values()) is the whole load.

Rank the categories
Works for any manifest
You're not logged in, so your progress is kept in this browser only. Log in to save it, and to use hints and solutions.

Hints

Modifying Dictionaries

modifying-dictionaries.py
# A mission record that changes as the mission goes on
parker = {
    "name": "Parker Solar Probe",
    "launched": 2018,
    "orbits": 20,
    "status": "cruising",
}

# Assign to a key that does not exist yet and it gets added
parker["closest_km"] = 6100000
print(parker)

# The same syntax on an existing key overwrites the old value
parker["status"] = "perihelion pass"
parker["orbits"] = 21
print("Status:", parker["status"], "after", parker["orbits"], "orbits")

# update() applies several changes in one go
parker.update({"speed_kmh": 692000, "status": "record holder"})
print("Speed:", parker["speed_kmh"], "km/h")

# pop() removes a key and hands the value back to you
old_status = parker.pop("status")
print("Removed status was:", old_status)

# del removes a key without giving anything back
del parker["launched"]
print(parker)

# setdefault() only fills in a key that is missing
parker.setdefault("agency", "NASA")
parker.setdefault("name", "Something Else")
print("Name:", parker["name"], "| Agency:", parker["agency"])
Open the full example
script.py
PythonLn 1, Col 1Spaces: 4
Loading the Python environment…

Separate arguments with commas. They're passed on every Run as sys.argv[1:].