Lesson 7 of 15

Basic Counting

The Art of Counting

Combinatorics answers the question: how many ways can something happen?

Fundamental Rules

Product rule: If task A can be done in mm ways and task B in nn ways independently, together there are mnm \cdot n ways.

Sum rule: If task A can be done in mm ways OR task B in nn ways (mutually exclusive), there are m+nm + n ways total.

Permutations and Combinations

Permutation P(n,r)P(n, r) — ordered arrangements of rr items from nn: P(n,r)=n!(nr)!P(n, r) = \frac{n!}{(n-r)!}

Combination C(n,r)=(nr)C(n, r) = \binom{n}{r} — unordered selections of rr items from nn: (nr)=n!r!(nr)!\binom{n}{r} = \frac{n!}{r!(n-r)!}

Arrangements with repetitionrr choices from nn options with replacement: nrn^r

import math

def permutations(n, r):
    return math.factorial(n) // math.factorial(n - r)

def combinations(n, r):
    return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))

def arrangements_with_repetition(n, r):
    return n ** r

print(permutations(5, 3))   # 60  (5×4×3)
print(combinations(10, 3))  # 120

Your Task

Implement permutations(n, r), combinations(n, r), and arrangements_with_repetition(n, r).

Pyodide loading...
Loading...
Click "Run" to execute your code.