Python contest starter

Algorithm templates

Read the invariant, adapt a tested implementation and try a related problem.

Python contest starter

One stdin read, a typed token reader and a named debug print.

Python · Contest starter
starter.py
from collections import Counter, defaultdict
import sys, inspect
sys.setrecursionlimit(10**7)
INF = 10**18
MOD = 10**9 + 7

def debug(*args):
    """Print the call's argument names and values to standard error."""
    frame = inspect.currentframe().f_back
    info = inspect.getframeinfo(frame)
    line = info.code_context[0].strip()
    expr = line[line.find('debug(') + 6 : line.rfind(')')]
    names = [n.strip() for n in expr.split(',')]

    def _fmt(x):
        if isinstance(x, dict):
            return '{' + ', '.join(f"{_fmt(k)}: {_fmt(v)}" for k, v in x.items()) + '}'
        if isinstance(x, (list, tuple, set)):
            openb, closeb = ('[', ']') if isinstance(x, list) else ('(', ')') if isinstance(x, tuple) else ('{', '}')
            return openb + ', '.join(_fmt(v) for v in x) + closeb
        return str(x)

    vals = ', '.join(_fmt(v) for v in args)
    print(f"[{', '.join(names)}] = [{vals}]", file=sys.stderr)

_data = sys.stdin.read().split()
_it = iter(_data)

def read(*types):
    """read(int) returns one value; read(int, int) returns a tuple."""
    vals = [t(next(_it)) for t in types]
    return vals[0] if len(vals) == 1 else tuple(vals)


def solve():
    n = read(int)

def main():
    MULTITEST = False
    t = read(int) if MULTITEST else 1
    for _ in range(t):
        solve()

if __name__ == "__main__":
    main()

read(int) returns one value and read(int, int) returns a tuple. Set MULTITEST = True when the input starts with a test count.