Skip to main content

comb, perm, factorial, prod

math.comb(n, k) and math.perm(n, k) compute nCk and nPk exactly with big ints; math.factorial and math.prod cover n! and products. Use them for counting problems (unique paths, Pascal's triangle) instead of hand-rolled loops.

Syntax​

import math

math.comb(5, 2) # -> 10 n! / (k! (n-k)!)
math.perm(5, 2) # -> 20 n! / (n-k)!
math.factorial(5) # -> 120
math.prod([2, 3, 4]) # -> 24

Edge cases​

import math

math.comb(5, 0) # -> 1
math.comb(3, 5) # -> 0 k > n
math.perm(5) # -> 120 k defaults to n
math.prod([]) # -> 1
math.prod([1, 2, 3], start=10) # -> 60
# negative args raise ValueError

Unique paths (LC 62) in O(min(m, n))​

import math

def unique_paths(m: int, n: int) -> int:
return math.comb(m + n - 2, m - 1) # choose which moves go down

unique_paths(3, 7) # -> 28

Pascal's triangle values​

import math

def pascal_row(n: int) -> list[int]: # LC 119
return [math.comb(n, k) for k in range(n + 1)]

pascal_row(4) # -> [1, 4, 6, 4, 1]

def generate(num_rows: int) -> list[list[int]]: # LC 118, O(n^2)
rows = [[1]]
for _ in range(num_rows - 1):
prev = rows[-1]
rows.append([1] + [a + b for a, b in zip(prev, prev[1:])] + [1])
return rows

generate(4) # -> [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]

Catalan numbers (unique BSTs, LC 96)​

import math

def catalan(n: int) -> int:
return math.comb(2 * n, n) // (n + 1)

[catalan(i) for i in range(6)] # -> [1, 1, 2, 5, 14, 42]

Large results modulo a prime​

import math

MOD = 10**9 + 7
math.comb(1000, 500) % MOD # fine for moderate n; for many queries precompute
# factorials mod p (see Modular arithmetic)

Docs​