Algorithms

Contents

Algorithms#

The standard library covers most everyday algorithmic needs. sorted, bisect, heapq, itertools, functools, hashlib, and graphlib together handle sorting, searching, ordered sequences, priority queues, lazy combinators, memoization, graph traversal, and hashing. Reach for them before rolling your own.

This section breaks the catalogue into one page per algorithm family. For the containers the algorithms run over, see Data Structures.

Family#

Sorting

Timsort, sort / sorted, custom keys, itemgetter / attrgetter, stable multi-key sorting.

Sorting
Searching

Linear, in, bisect_left / bisect_right, insort, set / dict for repeated membership.

Searching
Recursion

setrecursionlimit, memoization with @cache and @lru_cache.

Recursion
Dynamic programming

Top-down memoization vs bottom-up tabulation. LCS, edit distance, knapsack, coin change.

Dynamic programming
Greedy

Interval scheduling, token bucket, when greedy is correct.

Greedy
Graphs

Adjacency representation, BFS, DFS, Dijkstra, graphlib.TopologicalSorter.

Graphs
Strings

Built-in methods, regex, substring search, distance metrics.

Strings
Hashing

hash vs hashlib, content addressing, password stretching, HMAC.

Hashing
Rate limiting

Token bucket, leaky bucket, sliding window.

Rate limiting
Scheduling

Bounded concurrency with asyncio.Semaphore and ThreadPoolExecutor.

Scheduling
Parsing

Built-ins, regex, and real parsers. When each tier earns its place.

Parsing
Big-O

Common-operation complexities for built-in containers in CPython.

Big-O

References#