11.4.3. Homework#
Use this assignment to practice the chapter’s concepts and coding skills in runnable Python code.
Sign in from the account menu before you start working on the assignment.
Write and run your code directly in the coding cells.
Multiple submissions are allowed. The highest score is kept.
1. Iterator Protocol
An object used with repeated next() calls is acting through the iterator protocol.
2. Laziness
You run squares = (n * n for n in range(10_000_000)). The line finishes almost instantly because no squares have been computed yet.
3. StopIteration
A custom iterator should return the string "done" forever when it runs out of values.
4. Generator Expressions
total = sum(x * 2 for x in values) adds up the doubled values without first building a list of all of them.
5. Yield
count_up is a function whose body contains yield. After gen = count_up(3) runs, the body of count_up has already run to the end.
### 6. Skip a header with `iter` and `next`
# The rows below come from a CSV file. Create an iterator over `rows`, use `next()`
# once to read the header, then loop over the same iterator to print only the
# name from each remaining row.
# Print exactly these three lines:
# Header: name,score
# Ana
# Bob
rows = ["name,score", "Ana,88", "Bob,72"]
### Your code starts here.
### Your code ends here.
### 7. Write a cleaning generator function
# Define a generator function `clean_names(names)` that strips the spaces from
# each name, skips names that are empty after stripping, and yields the rest
# with only the first letter capitalized (use `str.capitalize()`).
# Collect the results with `list()`.
# Print exactly this line:
# Names: ['Ana', 'Bob', 'Cy']
raw = [" ana", "", "BOB ", " ", "cy"]
### Your code starts here.
### Your code ends here.
### 8. Use a generator expression
# Sum only positive values using a generator expression.
# Print exactly this line:
# Positive total: 14
values = [10, -3, 4, -1]
### Your code starts here.
### Your code ends here.
### 9. Fix iterator exhaustion
# This code adds a $3 shipping fee to each price, then reuses the same generator:
# shipped = (p + 3 for p in prices)
# print("Total:", sum(shipped))
# print("Largest:", max(shipped)) # ValueError: max() iterable argument is empty
# The second pass fails because `sum()` already exhausted the generator.
# Write a function `shipped_prices(prices)` that returns a fresh generator
# expression each time it is called, and use it for both results.
# Print exactly these two lines:
# Total: 34
# Largest: 15
prices = [12, 5, 8]
### Your code starts here.
### Your code ends here.
### 10. Build a generator pipeline
# Build a three-stage generator pipeline over the `ORDERS` text:
# 1. Generator function `parse_orders(text)`: skip the header row and
# yield one `(item, qty)` tuple per line, with `qty` as an `int`.
# 2. Generator function `large_orders(orders, minimum)`: yield only the
# tuples whose `qty` is at least `minimum`.
# 3. Generator function `shout(orders)`: yield `(item.upper(), qty)`.
# Write `pipeline(text, minimum)` that connects the three stages and returns
# the last one. With `minimum` 3, build a fresh pipeline for each result:
# a list of the item names, the total quantity with `sum()`, and the largest
# quantity with `max()`.
# Print exactly these lines:
# Items: ['PEN', 'MUG', 'PEN', 'BOOK']
# Total quantity: 18
# Largest order: 6
ORDERS = """item,qty
pen,5
book,2
mug,4
pen,3
lamp,1
book,6"""
### Your code starts here.
### Your code ends here.