Pure Python implementations of competitive programming algorithms.
Optimizing pure CPython code is far from intuitive.
In most other languages, you may rely on compilers for various small yet extremely useful optimizations, such as constant propagation, variable lookup, arithmetic operations etc…. However, CPython’s bytecode compiler is doing a bare minimum job, without doing any significant optimizations.
These are the most important tips.
sum
or max
, for example.Whether the absolute value of an integer is less than $2^{30}$ or not heavily affects the performance, as that’s the size of a digit CPython uses. Hence, it is extremely important to distinguish between “small” integers (absolute value less than $2^{30}$) and “large” integers.
x
and not x
for condition expressions.not not x
to convert x
to a boolean. Do not use bool(x)
, nor x != 0
.x&1
, refrain from using bitwise operations for small integers.
%
and //
over &
and >>
.divmod
for small integers. (Function calls are really expensive.)divmod
when the second argument is a power of 2.divmod
for large integers with non-power-of-2 second argument.for _ in itertools.repeat(None, N)
over for _ in range(N)
.enumerate(A)
or range(len(A))
.