Project 3 · Practice

Quiz & exercises

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

Quiz

1. What does this print?
from collections import namedtuple
try:
    T = namedtuple('T', ['Plate ID', 'Make'])
    print('ok')
except ValueError as ex:
    print('ValueError')
2. What does this print?
values = [4006478550, '', 0]
print(all(values), all(v is not None for v in values))
3. What does this print?
from collections import defaultdict
d = defaultdict(int)
d['FORD'] += 1
d['FORD'] += 1
d['BMW']
print(dict(d))
4. What does this print?
from functools import partial

def parse_string(value, *, default=None):
    cleaned = value.strip()
    return cleaned if cleaned else default

parse_optional = partial(parse_string, default='')
print(repr(parse_string('   ')), repr(parse_optional('   ')), repr(parse_optional(' NY ')))
5. What does this print?
counts = {'GMC': 35, 'TOYOT': 112, 'HYUND': 35, 'BMW': 34}
ranked = sorted(counts.items(), key=lambda t: t[1], reverse=True)
print([make for make, _ in ranked])
6. In the row parser, why is the parsed data built with a list comprehension rather than a generator expression?
7. The issue dates are left as strings like '10/5/2016' and '9/30/2016'. What does min(['10/5/2016', '9/30/2016']) return?

Coding exercises

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

Exercise 1: Parsers with defaults

Write three parser functions. Each takes a string value and a keyword-only argument default (which defaults to None), and returns default instead of raising when the value can't be parsed.

- parse_int(value, *, default=None): the value as an int. - parse_date(value, *, default=None): the value as a datetime.date; dates are in month/day/year format such as '10/5/2016'. - parse_string(value, *, default=None): the value with leading/trailing whitespace removed, or default if nothing is left.

Hints (3)
  1. Put a bare * before default in the parameter list to make it keyword-only.
  2. Wrap the conversion in try / except ValueError and return default in the except branch.
  3. datetime.strptime(value, '%m/%d/%Y') returns a datetime; call .date() on it.
Show a solution
from datetime import datetime

def parse_int(value, *, default=None):
    try:
        return int(value)
    except ValueError:
        return default

def parse_date(value, *, default=None):
    try:
        return datetime.strptime(value, '%m/%d/%Y').date()
    except ValueError:
        return default

def parse_string(value, *, default=None):
    cleaned = value.strip()
    return cleaned if cleaned else default

Exercise 2: Header and row parser

The parsers from the previous exercise and the tuple column_parsers (one parser per column) are provided.

1. Write make_field_names(header_line) that turns the raw header line (with its trailing '\n') into a list of field names: split on commas, replace spaces with underscores, lower-case. 2. Create a named tuple class Ticket from the header of nyc_parking_tickets_extract.csv. 3. Write parse_row(row, *, default=None) that parses one raw data line (with its '\n') into a Ticket, applying the i-th parser to the i-th field. If any parsed value is None, return default instead. Empty strings produced by the optional-column parsers are valid.

Hints (3)
  1. Strip the '\n' before splitting, both in the header and in each row.
  2. zip(column_parsers, fields) pairs each parser with its field: [func(field) for func, field in zip(...)].
  3. Use all(v is not None for v in parsed), not all(parsed): empty strings are valid values.
Show a solution
from collections import namedtuple
from datetime import datetime
from functools import partial

def parse_int(value, *, default=None):
    try:
        return int(value)
    except ValueError:
        return default

def parse_date(value, *, default=None):
    try:
        return datetime.strptime(value, '%m/%d/%Y').date()
    except ValueError:
        return default

def parse_string(value, *, default=None):
    cleaned = value.strip()
    return cleaned if cleaned else default

column_parsers = (
    parse_int,                              # summons_number
    parse_string,                           # plate_id
    partial(parse_string, default=''),      # registration_state
    partial(parse_string, default=''),      # plate_type
    parse_date,                             # issue_date
    parse_int,                              # violation_code
    partial(parse_string, default=''),      # vehicle_body_type
    parse_string,                           # vehicle_make
    partial(parse_string, default=''),      # violation_description
)

file_name = 'nyc_parking_tickets_extract.csv'

def make_field_names(header_line):
    headers = header_line.strip('\n').split(',')
    return [header.replace(' ', '_').lower() for header in headers]

with open(file_name) as f:
    Ticket = namedtuple('Ticket', make_field_names(next(f)))

def parse_row(row, *, default=None):
    fields = row.strip('\n').split(',')
    parsed = [func(field) for func, field in zip(column_parsers, fields)]
    if all(value is not None for value in parsed):
        return Ticket(*parsed)
    return default

Exercise 3: Goal 1: the lazy Ticket iterator

Ticket and parse_row(row, *, default=None) are provided (as in the previous exercise).

1. Write a generator read_data(file_name) that opens the file, skips the header line and yields the remaining raw lines. Use yield from. 2. Write a generator parsed_data(file_name) that yields a Ticket for every valid row of the file, skipping rows that parse_row rejects.

Both must be lazy: never read the whole file into a list.

Hints (2)
  1. Inside the with block, call next(f) once to skip the header, then yield from f.
  2. parsed_data loops over read_data(file_name), calls parse_row and yields only results that are not None.
Show a solution
from collections import namedtuple
from datetime import datetime
from functools import partial

def parse_int(value, *, default=None):
    try:
        return int(value)
    except ValueError:
        return default

def parse_date(value, *, default=None):
    try:
        return datetime.strptime(value, '%m/%d/%Y').date()
    except ValueError:
        return default

def parse_string(value, *, default=None):
    cleaned = value.strip()
    return cleaned if cleaned else default

column_parsers = (
    parse_int, parse_string,
    partial(parse_string, default=''), partial(parse_string, default=''),
    parse_date, parse_int,
    partial(parse_string, default=''), parse_string,
    partial(parse_string, default=''),
)

with open('nyc_parking_tickets_extract.csv') as f:
    headers = next(f).strip('\n').split(',')
Ticket = namedtuple('Ticket', [h.replace(' ', '_').lower() for h in headers])

def parse_row(row, *, default=None):
    fields = row.strip('\n').split(',')
    parsed = [func(field) for func, field in zip(column_parsers, fields)]
    if all(value is not None for value in parsed):
        return Ticket(*parsed)
    return default

# --- your code below ---

def read_data(file_name):
    with open(file_name) as f:
        next(f)          # skip the header
        yield from f

def parsed_data(file_name):
    for row in read_data(file_name):
        ticket = parse_row(row)
        if ticket is not None:
            yield ticket

Exercise 4: Goal 2: violations by car make

The complete Goal 1 pipeline is provided: parsed_data(file_name) yields Ticket named tuples.

Write violation_counts_by_make(file_name) that returns a dict mapping each vehicle_make to its number of tickets, with the keys ordered from the highest count to the lowest. Consume the tickets lazily in a single pass; don't build a list of tickets.

Hints (3)
  1. defaultdict(int) lets you write counts[make] += 1 without checking whether the key exists.
  2. Sort the items by count: sorted(counts.items(), key=lambda item: item[1], reverse=True), then build a dict from the sorted pairs (dicts keep insertion order).
  3. Alternatively: dict(Counter(t.vehicle_make for t in parsed_data(file_name)).most_common()).
Show a solution
from collections import namedtuple, defaultdict, Counter
from datetime import datetime
from functools import partial

def parse_int(value, *, default=None):
    try:
        return int(value)
    except ValueError:
        return default

def parse_date(value, *, default=None):
    try:
        return datetime.strptime(value, '%m/%d/%Y').date()
    except ValueError:
        return default

def parse_string(value, *, default=None):
    cleaned = value.strip()
    return cleaned if cleaned else default

column_parsers = (
    parse_int, parse_string,
    partial(parse_string, default=''), partial(parse_string, default=''),
    parse_date, parse_int,
    partial(parse_string, default=''), parse_string,
    partial(parse_string, default=''),
)

with open('nyc_parking_tickets_extract.csv') as f:
    headers = next(f).strip('\n').split(',')
Ticket = namedtuple('Ticket', [h.replace(' ', '_').lower() for h in headers])

def parse_row(row, *, default=None):
    fields = row.strip('\n').split(',')
    parsed = [func(field) for func, field in zip(column_parsers, fields)]
    if all(value is not None for value in parsed):
        return Ticket(*parsed)
    return default

def read_data(file_name):
    with open(file_name) as f:
        next(f)
        yield from f

def parsed_data(file_name):
    for row in read_data(file_name):
        ticket = parse_row(row)
        if ticket is not None:
            yield ticket

# --- your code below ---

def violation_counts_by_make(file_name):
    counts = defaultdict(int)
    for ticket in parsed_data(file_name):
        counts[ticket.vehicle_make] += 1
    return {make: count
            for make, count in sorted(counts.items(),
                                      key=lambda item: item[1],
                                      reverse=True)}