Project 4 · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
import csv
line = '"Kohler, Bradtke and Davis",Support,80-0975518'
print(len(line.split(',')), len(next(csv.reader([line]))))
2. What does this print?
from itertools import chain, compress
masks = ([True, False], [False, True])
mask = chain.from_iterable(masks)
rows = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]
for row in rows:
    print(list(compress(row, mask)))
3. Three aligned generators yield named tuples A, B and C records. What is each item of zip(gen_a, gen_b, gen_c)?
4. What does this print?
from itertools import groupby
makes = ['Ford', 'GMC', 'Ford', 'Ford', 'GMC']
print([(k, len(list(g))) for k, g in groupby(makes)])
5. What does this print?
from functools import partial

def filter_key(min_year, make, row):
    return row[0] == make and row[1] >= min_year

is_new_ford = partial(filter_key, 2000, 'Ford')
rows = [('Ford', 1997), ('Ford', 2005), ('GMC', 2010)]
print(list(filter(is_new_ford, rows)))
6. A generator function opens a file with with open(...) as f: and does yield from csv.reader(f). When is the file closed?
7. You parse last_updated with datetime.fromisoformat('2017-10-07T00:14:42Z') (Python 3.11+), then test row.last_updated >= datetime(2017, 3, 1). What happens?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Goal 1: typed iterators per file

Write two functions:

- parse_date(value) converts a string like '2017-10-07T00:14:42Z' into a naive datetime (no time zone). - iter_file(fname, class_name, parser) is a generator that lazily reads the CSV file fname and yields one named tuple per data row. The named tuple class is called class_name and its field names come from the file's header row. parser is a tuple of one-argument functions, one per column, used to convert each value.

For example, iter_file('data/vehicles.csv', 'Vehicle', (str, str, str, int)) should first yield Vehicle(ssn='100-53-9824', vehicle_make='Oldsmobile', vehicle_model='Bravada', model_year=1993).

Some employer names contain commas inside quotes, so use the csv module rather than split(',').

Hints (3)
  1. datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ') parses the dates; the Z is matched literally.
  2. Read the header with next(csv.reader(f)) and pass that list straight to namedtuple(class_name, header).
  3. zip(row, parser) pairs each raw string with its converter; unpack the converted values into the class with *.
Show a solution
import csv
from collections import namedtuple
from datetime import datetime

def parse_date(value, *, fmt='%Y-%m-%dT%H:%M:%SZ'):
    return datetime.strptime(value, fmt)

def csv_parser(fname, *, include_header=False):
    with open(fname) as f:
        reader = csv.reader(f, delimiter=',', quotechar='"')
        if not include_header:
            next(reader)
        yield from reader

def iter_file(fname, class_name, parser):
    header = next(csv_parser(fname, include_header=True))
    nt_class = namedtuple(class_name, header)
    for row in csv_parser(fname):
        yield nt_class(*(parse_fn(value) for value, parse_fn in zip(row, parser)))

Exercise 2: Goal 2: one combined iterator

The starter contains a working Goal 1 solution and the per-file constants. Write a generator function iter_combined() that yields one named tuple per person, combining all four files. The class must be called Data, and its fields must be, in this order:

ssn, first_name, last_name, gender, language, employer, department, employee_id, vehicle_make, vehicle_model, model_year, last_updated, created

That is: all personal fields, then the other files' fields in file order, with ssn appearing only once. The files are aligned (row k is the same person in every file), so you don't need to match SSNs. Keep the converted types from Goal 1.

Hints (3)
  1. zip(*file_iters) yields a tuple of four records (one per file) for each person.
  2. itertools.chain.from_iterable(records) flattens the four records into one stream of values.
  3. Build a Boolean mask (one entry per column across all four headers) that is False for the extra ssn columns, store it as a tuple, and use itertools.compress on both the header names and every row.
Show a solution
import csv
import itertools
from collections import namedtuple
from datetime import datetime

def parse_date(value, *, fmt='%Y-%m-%dT%H:%M:%SZ'):
    return datetime.strptime(value, fmt)

def csv_parser(fname, *, include_header=False):
    with open(fname) as f:
        reader = csv.reader(f, delimiter=',', quotechar='"')
        if not include_header:
            next(reader)
        yield from reader

def extract_field_names(fname):
    return next(csv_parser(fname, include_header=True))

def iter_file(fname, class_name, parser):
    nt_class = namedtuple(class_name, extract_field_names(fname))
    for row in csv_parser(fname):
        yield nt_class(*(parse_fn(value) for value, parse_fn in zip(row, parser)))

FNAMES = ('data/personal_info.csv', 'data/employment.csv',
          'data/vehicles.csv', 'data/update_status.csv')
CLASS_NAMES = ('Personal', 'Employment', 'Vehicle', 'UpdateStatus')
PARSERS = ((str, str, str, str, str), (str, str, str, str),
           (str, str, str, int), (str, parse_date, parse_date))

def iter_combined():
    headers = [extract_field_names(fname) for fname in FNAMES]
    # keep every column of the first file, and every non-ssn column of the others
    mask = tuple(i == 0 or name != 'ssn'
                 for i, header in enumerate(headers) for name in header)
    all_fields = itertools.chain.from_iterable(headers)
    Data = namedtuple('Data', itertools.compress(all_fields, mask))

    file_iters = (iter_file(fname, class_name, parser)
                  for fname, class_name, parser in zip(FNAMES, CLASS_NAMES, PARSERS))
    for records in zip(*file_iters):
        values = itertools.chain.from_iterable(records)
        yield Data(*itertools.compress(values, mask))

Exercise 3: Goal 3: only current records

The starter contains a working iter_combined() from Goal 2. Write a generator function iter_current(cutoff=datetime(2017, 3, 1)) that yields only the current combined records: those whose last_updated is on or after cutoff. Records updated before the cutoff are stale and must be skipped.

Keep it lazy: don't build a list of all records.

Hints (3)
  1. last_updated is already a datetime, so you can compare it with cutoff directly.
  2. filter(predicate, iter_combined()) is lazy; yield from it, or return it.
  3. Stale means last_updated < cutoff, so current means >=.
Show a solution
import csv
import itertools
from collections import namedtuple
from datetime import datetime

def parse_date(value, *, fmt='%Y-%m-%dT%H:%M:%SZ'):
    return datetime.strptime(value, fmt)

def csv_parser(fname, *, include_header=False):
    with open(fname) as f:
        reader = csv.reader(f, delimiter=',', quotechar='"')
        if not include_header:
            next(reader)
        yield from reader

def extract_field_names(fname):
    return next(csv_parser(fname, include_header=True))

def iter_file(fname, class_name, parser):
    nt_class = namedtuple(class_name, extract_field_names(fname))
    for row in csv_parser(fname):
        yield nt_class(*(parse_fn(value) for value, parse_fn in zip(row, parser)))

FNAMES = ('data/personal_info.csv', 'data/employment.csv',
          'data/vehicles.csv', 'data/update_status.csv')
CLASS_NAMES = ('Personal', 'Employment', 'Vehicle', 'UpdateStatus')
PARSERS = ((str, str, str, str, str), (str, str, str, str),
           (str, str, str, int), (str, parse_date, parse_date))
MASKS = ((True, True, True, True, True), (True, True, True, False),
         (False, True, True, True), (False, True, True))

def iter_combined():
    mask = tuple(itertools.chain.from_iterable(MASKS))
    fields = itertools.chain.from_iterable(extract_field_names(f) for f in FNAMES)
    Data = namedtuple('Data', itertools.compress(fields, mask))
    file_iters = (iter_file(f, c, p) for f, c, p in zip(FNAMES, CLASS_NAMES, PARSERS))
    for records in zip(*file_iters):
        yield Data(*itertools.compress(itertools.chain.from_iterable(records), mask))

def iter_current(cutoff=datetime(2017, 3, 1)):
    yield from filter(lambda row: row.last_updated >= cutoff, iter_combined())

Exercise 4: Goal 4: the largest car make groups per gender

Write largest_make_groups(records). records is any iterable (possibly a one-shot generator) of objects with gender and vehicle_make attributes, such as the current records from Goal 3.

Return a dictionary mapping each gender that appears to a tuple (count, makes), where count is the size of that gender's largest make group and makes is an alphabetically sorted list of every make with that count (there may be ties). An empty input returns {}.

Example: for records (F, Ford), (F, GMC), (M, Ford), (F, Ford), (M, Kia), (F, GMC) the result is {'F': (2, ['Ford', 'GMC']), 'M': (1, ['Ford', 'Kia'])}.

Practice sorted + itertools.groupby here rather than Counter. The tests also run your function on the project data.

Hints (3)
  1. records may be a generator, so read it only once, for example with sorted(records, key=...).
  2. Sorting by (gender, vehicle_make) lets you groupby gender first and then groupby make inside each gender group.
  3. Count each make group as you reach it with sum(1 for _ in group), then keep every make whose count equals the maximum.
Show a solution
import itertools

def largest_make_groups(records):
    key = lambda r: (r.gender, r.vehicle_make)
    ordered = sorted(records, key=key)       # one pass over a one-shot input
    result = {}
    for gender, gender_rows in itertools.groupby(ordered, key=lambda r: r.gender):
        counts = [(make, sum(1 for _ in rows))
                  for make, rows in itertools.groupby(gender_rows, key=lambda r: r.vehicle_make)]
        top = max(count for _, count in counts)
        result[gender] = (top, sorted(make for make, count in counts if count == top))
    return result