cs.oldnet

All sheets / Languages

Python

Syntax and idioms for coding rounds plus the language questions that come up.

Collections

xs = [3, 1, 2]; xs.append(4); xs.pop(); xs.sort(); sorted(xs, reverse=True)
d = {"a": 1}; d.get("b", 0); d.setdefault("k", []).append(1)
s = {1, 2}; s | t; s & t; s - t
t = (1, 2)            # immutable, hashable
from collections import Counter, defaultdict, deque, OrderedDict
Counter("aab").most_common(1)   # [('a', 2)]
g = defaultdict(list)
q = deque(); q.append(x); q.popleft()  # O(1) queue

Comprehensions & slicing

[x * x for x in xs if x % 2]
{k: v for k, v in pairs}
{x for x in xs}
(x for x in xs)             # lazy generator
xs[::-1]; xs[1:-1]; xs[::2]
for i, x in enumerate(xs): ...
for a, b in zip(xs, ys): ...

Heaps, bisect, sorting

import heapq
heapq.heappush(h, (prio, item)); heapq.heappop(h)  # min-heap
heapq.nlargest(k, xs); heapq.heapify(xs)
# max-heap: push negatives

import bisect
bisect.bisect_left(sorted_xs, x)   # first index >= x

people.sort(key=lambda p: (-p.age, p.name))
from functools import cmp_to_key, lru_cache, cache

Functions

def f(a, b=2, *args, key=None, **kwargs): ...
# never use a mutable default
def bad(x, acc=[]): ...      # shared across calls!
def good(x, acc=None): acc = acc or []

@cache                        # memoize (3.9+)
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)

Decorators & context managers

import functools, time
def timed(fn):
    @functools.wraps(fn)
    def wrap(*a, **kw):
        t = time.perf_counter()
        try: return fn(*a, **kw)
        finally: print(fn.__name__, time.perf_counter() - t)
    return wrap

from contextlib import contextmanager
@contextmanager
def opened(path):
    f = open(path)
    try: yield f
    finally: f.close()

Classes

from dataclasses import dataclass, field
@dataclass(frozen=True)
class Point:
    x: int
    y: int = 0
    tags: list = field(default_factory=list)

class Stack:
    def __init__(self): self._xs = []
    def __len__(self): return len(self._xs)
    def __repr__(self): return f"Stack({self._xs})"
    @property
    def top(self): return self._xs[-1]
    @classmethod
    def of(cls, *xs): s = cls(); s._xs = list(xs); return s

Generators

def chunks(xs, n):
    for i in range(0, len(xs), n):
        yield xs[i:i + n]
yield from other_gen()
import itertools as it
it.islice(g, 10); it.chain(a, b); it.groupby(sorted_xs, key)
it.permutations(xs, 2); it.combinations(xs, 2); it.product(a, b)

asyncio

import asyncio
async def fetch(i):
    await asyncio.sleep(1); return i
async def main():
    results = await asyncio.gather(*(fetch(i) for i in range(5)))
    async with asyncio.timeout(2): await fetch(1)   # 3.11+
asyncio.run(main())

GIL: one thread runs Python bytecode at a time. Threads help I/O-bound work; use multiprocessing / ProcessPoolExecutor for CPU-bound.

Typing

from typing import Optional, Iterable, Callable, TypedDict, Protocol
def first(xs: list[int]) -> int | None: ...
Handler = Callable[[str], None]

Gotchas

  • is checks identity, == checks equality. Use is None.
  • Copy: a[:] / copy.copy shallow, copy.deepcopy deep.
  • [[0] * n] * m shares rows → use [[0] * n for _ in range(m)].
  • Integers are unbounded; // floors toward -inf; -7 // 2 == -4.
  • Strings are immutable: build with "".join(parts).