11.3.3. Homework#
Use these questions after class to check your understanding of the chapter concepts and coding skills.
Sign in from the account menu before you start working on the homework.
Complete all true/false and coding questions before you submit the homework.
Launch Live Code (the rocket) to write and run code 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
A generator can produce values one at a time instead of building a full list immediately.
3. StopIteration
A custom iterator should return the string "done" forever when it runs out of values.
4. Generator Expressions
A generator expression is useful when a pipeline needs values lazily and does not need to store every intermediate result.
5. Yield
A function that contains yield behaves exactly like a normal function that immediately returns a list.
### 6. Use `iter` and `next`
# Create an iterator and read two values. Print exactly these two lines:
# # First: 10
# # Second: 20
values = [10, 20, 30]
### Your code starts here.
### Your code ends here.
First: 10
Second: 20
### 7. Write a generator function
# Define `countdown(n)`. Print exactly this line:
# # Countdown: [3, 2, 1]
### Your code starts here.
### Your code ends here.
Countdown: [3, 2, 1]
### 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.
Positive total: 14
### 9. Handle iterator exhaustion
# Catch `StopIteration`. Print exactly these three lines:
# # Ana
# # Bob
# # No more names
names = iter(["Ana", "Bob"])
### Your code starts here.
### Your code ends here.
Ana
Bob
No more names
### 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.
Items: ['PEN', 'MUG', 'PEN', 'BOOK']
Total quantity: 18
Largest order: 6