Python: Probability, Combinatorics

By Xah Lee. Date: .

Factorial

# 2023-05-03
# factorial

import math

for i in range(10):
    print(i, math.factorial(i))

# 0 1
# 1 1
# 2 2
# 3 6
# 4 24
# 5 120
# 6 720
# 7 5040
# 8 40320
# 9 362880

List Permutations

List all possible arrangement of n things.

# 2023-05-03

from itertools import permutations

xlist = [1, 2, 3, 4]

# returns all possible arrangement
xx = list(permutations(xlist))

for i in xx:
    print(i)

# (1, 2, 3, 4)
# (1, 2, 4, 3)
# (1, 3, 2, 4)
# (1, 3, 4, 2)
# (1, 4, 2, 3)
# (1, 4, 3, 2)
# (2, 1, 3, 4)
# (2, 1, 4, 3)
# (2, 3, 1, 4)
# (2, 3, 4, 1)
# (2, 4, 1, 3)
# (2, 4, 3, 1)
# (3, 1, 2, 4)
# (3, 1, 4, 2)
# (3, 2, 1, 4)
# (3, 2, 4, 1)
# (3, 4, 1, 2)
# (3, 4, 2, 1)
# (4, 1, 2, 3)
# (4, 1, 3, 2)
# (4, 2, 1, 3)
# (4, 2, 3, 1)
# (4, 3, 1, 2)
# (4, 3, 2, 1)

# returns all possible arrangement, but take only 2 items
x2 = list(permutations(xlist, 2))

for i in x2:
    print(i)

# (1, 2)
# (1, 3)
# (1, 4)
# (2, 1)
# (2, 3)
# (2, 4)
# (3, 1)
# (3, 2)
# (3, 4)
# (4, 1)
# (4, 2)
# (4, 3)

List Combinations

List all possible combination of taking k things out of n.

# 2023-05-03

from itertools import combinations

xlist = [1, 2, 3, 4, 5]

# all possible combination of taking 3 things
xx = combinations(xlist, 3)

for i in list(xx):
    print(i)

# (1, 2, 3)
# (1, 2, 4)
# (1, 2, 5)
# (1, 3, 4)
# (1, 3, 5)
# (1, 4, 5)
# (2, 3, 4)
# (2, 3, 5)
# (2, 4, 5)
# (3, 4, 5)

Binomial Coefficient (Combination Formula)

math.comb(n,k) gives the possible ways of taking k things out of n. (order does not matter.)

it is also the binomial coefficient of nth power, kth term. i.e. the coefficient of (x+1)^n.

# 2023-05-03

import math

# math.comb(n,k) compute the binomial coefficient of nth power, kth term
# (in combinatorics, n things take k)
print( "C({},{}) = {}".format (9, 3 , math.comb(9,3)))
print( )
# C(9,3) = 84

nn = 3
for i in range(nn+1):
     print( "C({},{}) = {}".format (nn, i , math.comb(nn,i)))
print( )

# C(3,0) = 1
# C(3,1) = 3
# C(3,2) = 3
# C(3,3) = 1

# HHHH---------------------------------------------------

nn = 4
for i in range(nn+1):
     print( "C({},{}) = {}".format (nn, i , math.comb(nn,i)))
print( )

# C(4,0) = 1
# C(4,1) = 4
# C(4,2) = 6
# C(4,3) = 4
# C(4,4) = 1

# HHHH---------------------------------------------------

nn = 5
for i in range(nn+1):
     print( "C({},{}) = {}".format (nn, i , math.comb(nn,i)))
print( )

# C(5,0) = 1
# C(5,1) = 5
# C(5,2) = 10
# C(5,3) = 10
# C(5,4) = 5
# C(5,5) = 1

Python, Statistics, Probability