Lab

7.5.2. Lab#

  • Use this lab to practice the chapter’s coding skills in runnable Python code.

  • Sign in from the account menu before you start working on the lab.

  • Launch Live Code (the rocket) to write and run code in the coding cells.

  • Multiple submissions are allowed. The highest score is kept.

### Question 1: Discounted price list
# A shop wants a discounted price list with uppercase item names.
# Build discounted as a dict comprehension from prices: keys are
# name.upper(), values are the price reduced by discount and rounded
# to 2 decimal places.
# Loop over discounted in sorted key order and print one line per
# item as "NAME: price". Print exactly these four lines:
# APPLE: 1.08
# BANANA: 0.45
# CHERRY: 1.8
# GRAPE: 0.72
prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00, "grape": 0.80}
discount = 0.10
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00, "grape": 0.80}
discount = 0.10

discounted = {name.upper(): round(price * (1 - discount), 2) for name, price in prices.items()}

for name in sorted(discounted):
    print(f"{name}: {discounted[name]}")
APPLE: 1.08
BANANA: 0.45
CHERRY: 1.8
GRAPE: 0.72
### Question 2: Invert the capitals dictionary
# capitals maps each state to its capital city. Build city_to_state
# by inverting capitals with a dict comprehension (city as key, state
# as value).
# Print the state for "Topeka" using city_to_state.
# Then loop over city_to_state in sorted key order and print one line
# per city as "city -> state". Print exactly these four lines:
# State for Topeka: Kansas
# Jefferson City -> Missouri
# Little Rock -> Arkansas
# Topeka -> Kansas
capitals = {"Missouri": "Jefferson City", "Kansas": "Topeka", "Arkansas": "Little Rock"}
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
capitals = {"Missouri": "Jefferson City", "Kansas": "Topeka", "Arkansas": "Little Rock"}

city_to_state = {city: state for state, city in capitals.items()}

print("State for Topeka:", city_to_state["Topeka"])
for city in sorted(city_to_state):
    print(f"{city} -> {city_to_state[city]}")
State for Topeka: Kansas
Jefferson City -> Missouri
Little Rock -> Arkansas
Topeka -> Kansas
### Question 3: Scores keyed by (name, subject)
# scores maps a (name, subject) tuple to a score.
# Print Alice's math score using the tuple key ("alice", "math").
# Then loop over scores.items(), unpack each key into name and subject,
# and add up each student's total and number of scores in two
# dictionaries. For each name in sorted order, compute the average
# and print it with one decimal place.
# Print exactly these three lines:
# Alice math score: 92
# alice average: 90.0
# bob average: 78.0
scores = {
    ("alice", "math"): 92, ("alice", "science"): 88,
    ("bob", "math"): 75, ("bob", "science"): 81,
}
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
scores = {
    ("alice", "math"): 92, ("alice", "science"): 88,
    ("bob", "math"): 75, ("bob", "science"): 81,
}

print("Alice math score:", scores[("alice", "math")])

totals = {}
counts = {}
for key, value in scores.items():
    name, subject = key
    totals[name] = totals.get(name, 0) + value
    counts[name] = counts.get(name, 0) + 1

for name in sorted(totals):
    average = totals[name] / counts[name]
    print(f"{name} average: {average:.1f}")
Alice math score: 92
alice average: 90.0
bob average: 78.0
### Question 4: Set algebra for event admission
# vip_members lists everyone with VIP status; attendees lists everyone
# who showed up.
# Build welcomed as the attendees who ARE vip_members (use .intersection()).
# Build turned_away as the attendees who are NOT vip_members
# (use .difference()).
# Print both as sorted lists so the order is predictable.
# Print exactly these two lines:
# Welcomed: ['ana', 'sam']
# Turned away: ['eli', 'zoe']
vip_members = {"maya", "li", "ana", "sam"}
attendees = {"sam", "zoe", "ana", "eli"}
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
vip_members = {"maya", "li", "ana", "sam"}
attendees = {"sam", "zoe", "ana", "eli"}

welcomed = attendees.intersection(vip_members)
turned_away = attendees.difference(vip_members)

print(f"Welcomed: {sorted(welcomed)}")
print(f"Turned away: {sorted(turned_away)}")
Welcomed: ['ana', 'sam']
Turned away: ['eli', 'zoe']
### Question 5: Update a nested student record
# student_record has a nested "grades" dictionary and a "clubs" list.
# Use .update() on student_record["grades"] to add a "history" grade
# of 78.
# Use .pop() on student_record to remove the "clubs" key and store
# the removed value in removed_clubs.
# Use .setdefault() on student_record to add an "advisor" key with
# the value "Dr. Lee" (only if it is not already present).
# Print removed_clubs, then the advisor, then each subject and grade
# in student_record["grades"] in sorted key order. Print exactly
# these five lines:
# Removed clubs: ['chess']
# Advisor: Dr. Lee
# history: 78
# math: 90
# science: 85
student_record = {
    "name": "Riya",
    "grades": {"math": 90, "science": 85},
    "clubs": ["chess"],
}
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
student_record = {
    "name": "Riya",
    "grades": {"math": 90, "science": 85},
    "clubs": ["chess"],
}

student_record["grades"].update({"history": 78})
removed_clubs = student_record.pop("clubs")
student_record.setdefault("advisor", "Dr. Lee")

print("Removed clubs:", removed_clubs)
print("Advisor:", student_record["advisor"])
for subject in sorted(student_record["grades"]):
    print(f"{subject}: {student_record['grades'][subject]}")
Removed clubs: ['chess']
Advisor: Dr. Lee
history: 78
math: 90
science: 85