Python Snippet

Combinations and Permutations

Difficulty: Easy

When the problem reads 'pick K of N' or 'order all N', the right reflex in Python is `itertools.combinations` or `itertools.permutations`. Both are lazy iterators, so they enumerate huge search spaces without materializing them. This entry walks combinations, permutations, and `combinations_with_replacement`, plus when each is the right tool.

Code Snippets
/

Combinations and Permutations

Combinations and Permutations

When the problem reads 'pick K of N' or 'order all N', the right reflex in Python is `itertools.combinations` or `itertools.permutations`. Both are lazy iterators, so they enumerate huge search spaces without materializing them. This entry walks combinations, permutations, and `combinations_with_replacement`, plus when each is the right tool.

Python
Easy
3 snippets
py-itertools
py-generators
iterators
py-standard-library

235 views

2

combinations(iterable, r) yields every r-length tuple of items in input order, with no repeats and no equivalent reorderings. The output count equals the binomial coefficient C(n, r), and the order matches the input order, so combinations of a sorted input is itself sorted. Reach for it whenever the question is 'how many ways to pick r things' and order does not matter (committee selection, edge enumeration in a graph, choosing K elements for a subset-sum check). The iterator is lazy: stopping the loop early avoids enumerating the rest.