×

python · level 3 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A tool you can is small pieces, each tested alone.

A real tool joins everything up. A generator streams the data, so a huge file never sits in memory. A dataclass gives each record a clear shape. argparse reads the options, and main catches expected errors and returns an exit code.

Before you ship it, test each piece on its own: the parser with good and bad lines, the counting with an empty input, main with a bad option. Small pure functions make that quick.

from collections import Counter
from dataclasses import dataclass

@dataclass(frozen=True)
class Visit:
    page: str
    seconds: int

def parse(lines):
    for line in lines:
        page, seconds = line.split(",")
        yield Visit(page, int(seconds))

print(Counter(v.page for v in parse(["/home,12", "/shop,40", "/home,5"])).most_common())

Each step can be tested on its own, with a short list standing in for a real file.