Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 8 · Summary and Coding Challenges

Summary and Coding Challenges

On this pageExercise 1 — Build a Newsroom Keyword Extractor (Counter + chain)Exercise 2 — Academic Grade DistributionExercise 3 — Support Center Queue SimulationExercise 4 — Market Basket Exploration Using CombinatoricsDatasetPart A — Co-Purchased Item Pairs (combinations)Part B — Pricing Strategy Grid (product)

Specialized data structures provide fast, elegant solutions to recurring programming patterns. They remove boilerplate, improve performance, and make code clearer. Whether you’re counting words with Counter, grouping data with defaultdict, modeling lightweight records with namedtuple, managing queues with deque, exploring structured iterations through itertools, handling priorities with heapq, or representing categories using enum, these tools help you write Python that is both efficient and expressive.

To consolidate these skills, the following challenges place you in real-world scenarios where you must combine Counter,defaultdict,namedtuple,deque,itertools,heapq, and Enum.

Exercise 1 — Build a Newsroom Keyword Extractor (Counter + chain)

Scenario:

You work as a data engineer in a digital newsroom. Editors send you article headlines grouped by category. You must determine which words are trending across the entire newsroom.

Task: Write a program that:

  1. Flattens all headlines from all categories into one sequence of words.
  2. Lowercase the text and use re.findall(r"[a-z]+", headline.lower()) to extract word tokens. This exercise deliberately uses ASCII words; apostrophes split words, so team's contributes team and s.
  3. Counts how often each word appears.
  4. Prints the 10 most frequent words.
  5. Prints how often the word “breaking” appears.

Starter Code:

from collections import Counter
from itertools import chain

headlines = {
    "world": [
        "Breaking news as climate summit begins",
        "Leaders discuss global policy changes",
    ],
    "tech": [
        "Breaking discoveries in AI research",
        "New device launch draws attention",
    ],
    "sports": [
        "Local team achieves historic victory",
        "Coach praises team's discipline",
    ],
}

# TODO: Flatten and normalize words
# TODO: Count frequencies
# TODO: Print top 10 words
# TODO: Print count of "breaking"
Listing 366 — Exercise 1 — Build a Newsroom Keyword Extractor (Counter + chain)

Expected Output:

Most common words:
breaking: 2
team: 2
news: 1
as: 1
climate: 1
...
Occurrences of 'breaking': 2
Listing 367 — Exercise 1 — Build a Newsroom Keyword Extractor (Counter + chain)

Exercise 2 — Academic Grade Distribution

Scenario:

A university course needs an automated report summarizing student performance. You receive raw name–score pairs and must produce structured grade records and a grade distribution table.

Task:

  1. Create a lightweight record structure for student data.
  2. Use the exercise scale A: 90–100, B: 80–89, C: 60–79, D: 50–59, F: below 50; reject scores outside 0–100. These bands are sample policy, not a universal grading standard.
  3. Convert raw scores into grades.
  4. Group students by grade.
  5. Print a summary such as:
Grade A: Alice, Eva
Grade B: Bob
Grade C: Dan
Listing 368 — Exercise 2 — Academic Grade Distribution

Starter Code:

from collections import namedtuple, defaultdict
from enum import Enum

Student = namedtuple("Student", ["name", "score", "grade"])

class Grade(Enum):
    # TODO: Add enum values here 
    pass

def score_to_grade(score):
    # TODO: implement grading logic
    pass

raw_scores = [
    ("Alice", 95),
    ("Bob", 78),
    ("Cara", 88),
    ("Dan", 62),
    ("Eva", 91),
]

# TODO: Build student records
# TODO: Group by grade
# TODO: Print the summary
Listing 369 — Exercise 2 — Academic Grade Distribution

Example Output:

Grade A: Alice, Eva
Grade B: Cara
Grade C: Bob, Dan
Listing 370 — Exercise 2 — Academic Grade Distribution

Exercise 3 — Support Center Queue Simulation

Scenario:

A customer support center receives two kinds of customers: - VIP customers (served first) - Regular customers (served in order of arrival)

You must simulate the service process.

Task: 1. Create a queue. 2. Add several regular customers and several VIP customers. 3. For this exercise, add cust_001, cust_002, cust_003, then add vip_001 and vip_002 with appendleft. The last VIP added is served first. If VIPs must keep arrival order, design a separate VIP queue instead. 4. Process customers in order until the queue is empty. 5. Print the exact service order.

Starter Code:

from collections import deque

queue = deque()

# TODO: Add customers
# queue.append(...)        # regular customer
# queue.appendleft(...)    # VIP customer

# TODO: Process all customers
Listing 371 — Exercise 3 — Support Center Queue Simulation

Example Output:

Serving: vip_002
Serving: vip_001
Serving: cust_001
Serving: cust_002
Serving: cust_003
Listing 372 — Exercise 3 — Support Center Queue Simulation

Exercise 4 — Market Basket Exploration Using Combinatorics

Scenario

You’re working as a data analyst for an online grocery store. Your task is to explore purchasing patterns using a single dataset:

  • First, enumerate the pairs of items in this one basket. Repeated observations across many baskets would be needed to measure frequency.
  • Then, explore all pricing strategy combinations the business might test for those same items.

This exercise uses the same dataset, but applies two different combinatorial tools.

Dataset

You receive a list of items purchased in a single basket:

basket = ["milk", "bread", "butter", "eggs"]
Listing 373 — Dataset

You also receive two sets of possible pricing parameters the business wants to experiment with:

discount_rates = [0.05, 0.10]   # 5% and 10%
bundle_sizes   = [2, 3]         # bundles of 2 or 3 items
Listing 374 — Dataset

Part A — Co-Purchased Item Pairs (combinations)

Identify all unique 2-item pairs from the basket. This is used later to evaluate which bundles might be meaningful for promotions.

Starter Code

from itertools import combinations

basket = ["milk", "bread", "butter", "eggs"]

# TODO: Generate all 2-item combinations
Listing 375 — Part A — Co-Purchased Item Pairs (combinations)

Example Output

('milk', 'bread')
('milk', 'butter')
('milk', 'eggs')
('bread', 'butter')
('bread', 'eggs')
('butter', 'eggs')
Listing 376 — Part A — Co-Purchased Item Pairs (combinations)

Part B — Pricing Strategy Grid (product)

Management wants to test every combination of: - discount rate - bundle size

Use itertools.product to generate all pricing strategies.

Starter Code

from itertools import product

discount_rates = [0.05, 0.10]
bundle_sizes   = [2, 3]

# TODO: Generate all discount–bundle combinations
Listing 377 — Part B — Pricing Strategy Grid (product)

Example Output

discount=0.05, bundle=2
discount=0.05, bundle=3
discount=0.10, bundle=2
discount=0.10, bundle=3