Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 63 ยท Contest Toolkit

Templates and Habits

Build a minimal Python contest template with fast input, small helper functions, clear names and no global mutable state, so your code stays short and readable.

In a contest you type the same few lines at the start of every problem: imports, fast input, a main function, a loop over test cases. A template saves that typing and, more importantly, removes whole categories of mistakes because the boring parts are already correct. Good habits do the same for the interesting parts. This lesson builds a small template, a few helpers worth keeping, and a set of coding habits that keep solutions short without turning them into puzzles.

Keep templates small. A 300-line template full of tools you barely remember is slower to use than ten lines you know by heart.

A minimal template

Python
import sys
input = sys.stdin.readline


def solve() -> None:
    n = int(input())
    a = list(map(int, input().split()))
    # ... compute the answer ...
    print(sum(a))


def main() -> None:
    for _ in range(int(input())):
        solve()


main()

Why this shape?

  • input = sys.stdin.readline makes reading fast (Python for Contests).
  • Everything lives inside functions, so variables are local and fast.
  • solve() handles exactly one test case. If the problem has a single test, call solve() directly. If it has t tests, the loop is already there.
  • The call to main() is at module level without the if __name__ guard: on a judge nobody imports your file, so the guard is optional.

For output-heavy problems, collect answers in a list and print once:

Python
def main() -> None:
    out = []
    for _ in range(int(input())):
        out.append(solve())
    print("\n".join(map(str, out)))

Here solve returns the answer instead of printing it, which also makes it easy to test, as the next demo shows.

Python The template in action with an input() stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The three tests print 4, 2 and 0: the spread of each array, with a single element giving zero. Because solve only consumes its own test case from the input, adding or removing tests never breaks it.

Helpers worth keeping

Keep a short list of helpers that you use constantly.

Python
def ints() -> list[int]:
    return list(map(int, input().split()))


def ceil_div(a: int, b: int) -> int:
    return -(-a // b)


def yes_no(flag: bool) -> str:
    return "YES" if flag else "NO"
  • ints() reads a line of integers. One short call replaces a longer expression everywhere.
  • ceil_div does integer ceiling division without floats: ceil_div(7, 2) is 4. Floats lose precision for big numbers, so never write math.ceil(a / b) when a can be near 10^18.
  • yes_no removes the chance of typing the wrong case.

Other candidates for a personal toolkit are gcd from math, a function that builds prefix sums, a Counter, and a modular power. Add a helper only after you have typed the same thing three times.

Python Why ceil_div avoids float errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For 10^18 + 1 divided by 10^9 the exact answer is 1000000001, because the division leaves a remainder of 1. The float version rounds the numerator to a nearby float first, loses that remainder and returns 1000000000. Integer arithmetic is exact in Python, so use it.

Habits that prevent bugs

Name things for what they mean

In a contest short names are fine, but they must be consistent. A small convention helps you read your own code under stress:

  • n, m, q for sizes taken from the statement; a, b for arrays; i, j, k for indexes.
  • l, r for interval ends (and write your convention in a comment: [l, r) or [l, r]).
  • dp, best, ans, cur for the usual roles.
  • Never use l where it can be confused with 1, if your font makes that hard to read; lo and hi are safer in binary search.

Avoid mutable global state

Global lists and counters that persist between test cases are a classic source of Wrong Answer: the second test starts with leftover data from the first. Keep everything the problem needs inside solve(), or pass it in as an argument. If you must have a global (for example a precomputed sieve that does not change), build it once, before the loop, and never modify it later.

Python Global state leaking between test cases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The buggy version gives [3, 1, 0] because the set survives between tests; the fixed one gives [3, 2, 1]. The first test looks fine in both, which is exactly why this bug survives the samples.

Keep code short but readable

Short code is faster to write and has fewer places for bugs, but there is a limit.

  • Prefer clear one-liners (sum, max, comprehensions) over cryptic ones. A chain of nested ternaries is a bug waiting to happen.
  • Use enumerate and zip rather than index arithmetic where you can.
  • Use tuples for small records: (cost, node) in a heap, (x, y) for coordinates.
  • Write a one-line comment for any non-obvious trick. During a contest you will forget why you wrote it in ten minutes.
  • Split a long solve into two or three small functions when the logic has distinct stages (parse, compute, format). Small functions can be tested separately.

Check before you submit

A quick routine before every submission costs seconds and saves penalties:

  1. Run the samples.
  2. Run a minimal case (n = 1) and a duplicate/equal-values case.
  3. Estimate the worst-case time against the statement's limits.
  4. Make sure no debug output goes to stdout.
  5. Reread the output format.
flowchart LR
    A["Template"] --> B["Read and plan"]
    B --> C["Write solve()"]
    C --> D["Samples"]
    D --> E["Edge cases"]
    E --> F["Complexity check"]
    F --> G["Submit"]

A fixed routine turns the end of every problem into a checklist instead of a guess.

Template extras you may add later

As you progress, you will add pieces for specific topics: a gcd and modular helper for number theory, a union-find class, a Fenwick tree, a sieve. Keep each as a short, tested block that you can paste only when needed; do not load them into every solution.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the template put the main logic inside functions?

    Local variable access is faster in CPython, and variables created inside solve() disappear after each test case, which prevents state from leaking.
  2. 2. What does -(-a // b) compute?

    Floor division rounds toward negative infinity. Negating before and after turns it into rounding up, with exact integer arithmetic.
  3. 3. Your solution passes the samples but fails on the second test case of a multi-test input in the judge. What is the most likely cause?

    State kept in a global survives from one test case to the next. Create per-test data inside solve().
  4. 4. Which is the best use of a contest template?

    A small template you know by heart is faster and safer than a huge one you do not fully remember.

Summary

  • A minimal template has fast input, a solve() for one test case and a main() loop.
  • Return answers from solve() and print them once at the end for speed and testability.
  • Keep a few tiny helpers (ints, ceil_div, yes_no) and add more only when you repeat yourself.
  • Avoid mutable globals; leftover state between test cases causes bugs that samples hide.
  • Name things consistently, write short but readable code, and comment any trick.
  • Finish every problem with the same checklist before you submit.

Next: Estimating Time and Memory