Standard Library Essentials Assessment
Test your knowledge of Python's most powerful built-in modules: collections, itertools, functools, datetime, re, and math.
Write a function word_freq(text) that returns a dictionary mapping each lowercased word to its count. Use collections.Counter. Ignore punctuation by keeping only alphabetic characters in each word (skip tokens that become empty).
The function group_anagrams(words) should return a list of groups (lists) where each group contains words that are anagrams of each other. The code below has two bugs -- find and fix them.
What does this code print?
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x + p.y)
print(p._replace(x=10).x)
print(isinstance(p, tuple))Write a function recent_items(stream, n) that takes an iterable stream and returns a list of the last n items. Use collections.deque with a maxlen.
The flatten function works but uses manual loops. Refactor it to use itertools.chain.from_iterable in a single return statement. Keep the same function signature and behavior.
What does this code print?
from itertools import product
colors = ['red', 'blue']
sizes = ['S', 'L']
result = ['-'.join(combo) for combo in product(colors, sizes)]
print(result)
print(len(list(product(range(3), repeat=2))))Write a function power_set(items) that returns a sorted list of all subsets (each subset is a sorted tuple). Include the empty tuple. Use itertools.combinations.
The function below should return the product of all numbers in a list, defaulting to 1 for an empty list. It has two bugs -- find and fix them.
Write a function fib(n) that returns the nth Fibonacci number (0-indexed: fib(0)=0, fib(1)=1). Decorate it with functools.lru_cache so repeated calls are O(1).
The function days_until(date_str) should return how many days remain from 2025-01-01 to the given date string (format YYYY-MM-DD). It has two bugs -- find and fix them.
What does this code print?
import re
pattern = r'(\d{3})-(\d{4})'
text = 'Call 555-1234 or 800-9999'
matches = re.findall(pattern, text)
print(matches)
print(re.sub(r'\d', 'X', 'Order #42 shipped'))The function below computes the hypotenuse and checks if a number is close to an integer, all using manual arithmetic. Refactor it to use math.hypot and math.isclose. Keep the same function signature and return values.