Homework

10.3.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. First-Class Functions

In ranked = sorted(players, key=score), the name score without parentheses passes the function itself, and sorted() calls it once for each player to get that player’s sort key.

2. Pure Functions

The function with_tax(prices) returns [round(p * 1.1, 2) for p in prices]. Calling it twice on the same list gives equal results and leaves prices unchanged, so it is a pure function.

3. Lambda

A teammate needs a sort key that strips whitespace, raises ValueError for an empty name, and otherwise returns the lowercase name. Writing it as a lambda passed to sorted() is the better choice than defining it with def.

4. Comprehensions

For names = ['ana', '', 'chen'], the comprehension [n.upper() for n in names if n != ''] builds the same list as list(map(lambda n: n.upper(), filter(lambda n: n != '', names))).

5. Decorators

With @log_calls written above def square(n):, the name square still refers to the original function. The wrapper runs only if you call log_calls(square) yourself.

### 6. Use a list comprehension
# Define `high_scores(scores)` with a list comprehension. It returns a new
# list of the scores that are at least 80, in their original order.
# Call it on the scores below.
# Print exactly this line:
# High scores: [92, 88]
scores = [72, 92, 65, 88]

### Your code starts here.



### Your code ends here.
### 7. Use map with a lambda
# Define `to_cents(prices)` that uses `map()` with a `lambda` to convert dollar
# prices to whole cents. It returns a list.
# Call it on the prices below.
# Print exactly this line:
# Cents: [1250, 399, 800]
prices = [12.5, 3.99, 8.0]

### Your code starts here.



### Your code ends here.
### 8. Count items with reduce
# Define `count_items(orders)` that uses `functools.reduce()` with a dictionary
# initializer to count how many times each item appears. Each step must
# return a new dictionary, `{**acc, item: acc.get(item, 0) + 1}`, not change
# one in place. Call it on the orders below.
# Print exactly this line:
# Counts: {'apple': 2, 'kiwi': 3, 'pear': 1}
from functools import reduce

orders = ['apple', 'kiwi', 'pear', 'apple', 'kiwi', 'kiwi']

### Your code starts here.



### Your code ends here.
### 9. Log calls with a decorator
# Import `wraps` from `functools`. Write a decorator `log_calls(func)`. Its
# wrapper uses `@wraps(func)` and accepts `*args`, calls `func(*args)`,
# appends the result to `call_log`, prints
# `f"Call {len(call_log)}: {func.__name__} -> {result}"`, and returns the result.
# Apply it with `@log_calls` to a function `add(a, b)` that returns `a + b`.
# Call `add(3, 4)` and `add(10, 5)`, then print `call_log` and `add.__name__`.
# Print exactly these lines:
# Call 1: add -> 7
# Call 2: add -> 15
# Results: [7, 15]
# Name: add
call_log = []

### Your code starts here.



### Your code ends here.
### 10. Write a context manager
# Import `contextmanager` from `contextlib`. Write a generator function
# `log_block(label)` decorated with `@contextmanager`. It prints
# `f"Start {label}"`, then yields inside `try`, and prints `f"End {label}"`
# in the `finally` clause so the end line prints even when the block
# raises an error.
# First, use `with log_block("load"):` to print `"Loading 3 rows"`.
# Then, inside `try`/`except ValueError as error`, use
# `with log_block("parse"):` to raise `ValueError("bad row")`, and in the
# `except` clause print `f"Caught: {error}"`.
# Print exactly these lines:
# Start load
# Loading 3 rows
# End load
# Start parse
# End parse
# Caught: bad row

### Your code starts here.



### Your code ends here.