Advanced Python

Level recap · Advanced Python · Level 1

Data structures that do the work

Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.

What this level teaches: Count, group, keep the last few and pick the smallest with the right built-in tool.

7 classesLevel exam

Take the level exam
  1. 1Count things with Counter

    collections.Counter.

    The idea

    Ticket PY-101 from the warehouse lead: from the list of product names on today's packing slips, which products went out most often?

    Counter(items) counts each value in one step: Counter(["Toner", "Shelf", "Toner"]) gives {"Toner": 2, "Shelf": 1}. Its .items() are (name, count) pairs. Sort them with key=lambda kv: (-kv[1], kv[0]): the minus sign puts the biggest count first, and the name breaks ties from A to Z. The result is a ranked list you can cut with [:n].

    The code

    from collections import Counter
    def top_products(lines, n):
        counts = Counter(lines)
        ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
        return ranked[:n]
    print(top_products(["Toner", "Shelf", "Toner", "Monitor"], 2))

    What it shows

    PASS Right on new test values
  2. 2Group with defaultdict

    collections.defaultdict.

    The idea

    Ticket PY-102 from customer care: group today's order numbers by customer, so each account manager gets one list.

    A normal dict raises KeyError the first time you add to a key that isn't there yet. defaultdict(list) makes an empty list for a new key on its own, so groups[customer].append(order_id) always works. Give back dict(groups) so the caller gets a plain dict.

    The code

    from collections import defaultdict
    def orders_by_customer(orders):
        groups = defaultdict(list)
        for customer, order_id in orders:
            groups[customer].append(order_id)
        return dict(groups)
    print(orders_by_customer([("Cedar Law", 412), ("Delta Gym", 415), ("Cedar Law", 588)]))

    What it shows

    PASS Right on new test values
  3. 3Keep only the last few: deque

    collections.deque with maxlen.

    The idea

    Ticket PY-103 from the platform team: the event stream never ends, and the support screen shows only the last few events. Keep those, without storing the whole stream.

    deque(items, maxlen=n) keeps at most n items: when a new one comes in, the oldest one drops out. It reads any stream, even one you can't slice, and uses memory for n items only. list(deque(events, maxlen=n)) gives the last n events.

    The code

    from collections import deque
    def recent(events, n):
        return list(deque(events, maxlen=n))
    print(recent(iter(["E1", "E2", "E3", "E4"]), 2))

    What it shows

    PASS Right on new test values
  4. 4Records with names: namedtuple

    collections.namedtuple.

    The idea

    Ticket PY-104 from finance: the order rows come in as plain tuples, and row[2] says nothing to the next person who reads the code. Give the fields names.

    Order = namedtuple("Order", "id customer total") makes a small record type. Order(17, "Cedar Law", 250) still works like a tuple, but you can write order.total instead of order[2]. Order(*row) turns a plain tuple into an Order.

    The code

    from collections import namedtuple
    Order = namedtuple("Order", "id customer total")
    def big_orders(rows, limit):
        return [Order(*row) for row in rows if row[2] >= limit]
    print(big_orders([(1, "Cedar Law", 640), (2, "Delta Gym", 90)], 500))

    What it shows

    PASS Right on new test values
  5. 5The smallest few: heapq

    heapq.nsmallest with a key.

    The idea

    Ticket PY-105 from purchasing: from a price list of hundreds of items, show the k cheapest, cheapest first. If two cost the same, A to Z.

    heapq.nsmallest(k, items, key=...) finds the k smallest items without sorting the whole list, which matters when the list is long. With a dict of prices, the items are the names, and key=lambda name: (prices[name], name) sorts by price, then by name.

    The code

    import heapq
    def cheapest(prices, k):
        return heapq.nsmallest(k, prices, key=lambda name: (prices[name], name))
    print(cheapest({"Toner": 45, "Notebooks": 4, "Shelf": 75}, 2))

    What it shows

    PASS Right on new test values
  6. 6Sort by several things at once

    A tuple as the sort key.

    The idea

    Ticket PY-106 from the sales director: the weekly leaderboard lists people team by team (A to Z), and inside each team the best seller first. Same sales: by name.

    sorted(items, key=f) sorts by what f gives for each item. A tuple key sorts by its first value, then the second for ties, and so on. A minus sign turns a number around, so (s["team"], -s["sales"], s["name"]) gives team A to Z, sales high to low, then name A to Z.

    The code

    def rank_staff(staff):
        ordered = sorted(staff, key=lambda s: (s["team"], -s["sales"], s["name"]))
        return [s["name"] for s in ordered]
    print(rank_staff([{"name": "Ana", "team": "South", "sales": 900}, {"name": "Ben", "team": "North", "sales": 500}]))

    What it shows

    PASS Right on new test values
  7. 7On your own: low stock alerts

    Track running totals, with no gold line.

    The idea

    Ticket PY-107 from the warehouse lead: every stock move is logged as (product, change), where a delivery is positive and a sale is negative. Every product starts at 0. Which products ended the day below the minimum? Plan it first: what do you keep for each product, and how do you pick the alerts?

    In the code box, write a function stock_alerts(moves, minimum) that gives back, sorted A to Z, the products whose final stock is below minimum. Only products that appear in moves count. Then press Run my code.

    The code

    from collections import defaultdict
    def stock_alerts(moves, minimum):
        stock = defaultdict(int)
        for product, change in moves:
            stock[product] += change
        return sorted(name for name, units in stock.items() if units < minimum)

    What it shows

    PASS Right on new test values

Ready for the exam? The level exam is one real task that uses what this recap covers.

Take the level exam