Skip to content

Commit e10e88a

Browse files
Robotcellclaude
andcommitted
Add Stirling numbers of the second kind
Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 30507bb commit e10e88a

1 file changed

Lines changed: 84 additions & 0 deletions

File tree

‎maths/stirling_numbers.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
"""
2+
Stirling numbers of the second kind: S(n, k) is the number of ways to partition a
3+
set of n labelled elements into exactly k non-empty, unlabelled subsets.
4+
5+
They satisfy S(n, k) = k * S(n - 1, k) + S(n - 1, k - 1): the n-th element either
6+
joins one of the k subsets of a partition of the first n - 1 elements, or forms a
7+
subset of its own.
8+
9+
https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
10+
"""
11+
12+
13+
def stirling_number_second_kind(n: int, k: int) -> int:
14+
"""
15+
Return S(n, k), the number of partitions of an n-element set into k subsets.
16+
17+
>>> stirling_number_second_kind(0, 0)
18+
1
19+
>>> stirling_number_second_kind(4, 2)
20+
7
21+
>>> stirling_number_second_kind(5, 3)
22+
25
23+
>>> stirling_number_second_kind(10, 5)
24+
42525
25+
>>> stirling_number_second_kind(6, 6)
26+
1
27+
>>> stirling_number_second_kind(6, 1)
28+
1
29+
>>> stirling_number_second_kind(3, 0)
30+
0
31+
>>> stirling_number_second_kind(3, 5)
32+
0
33+
>>> stirling_number_second_kind(30, 10)
34+
173373343599189364594756
35+
>>> stirling_number_second_kind(-1, 2)
36+
Traceback (most recent call last):
37+
...
38+
ValueError: n and k must be non-negative
39+
>>> stirling_number_second_kind(3, -1)
40+
Traceback (most recent call last):
41+
...
42+
ValueError: n and k must be non-negative
43+
"""
44+
if n < 0 or k < 0:
45+
raise ValueError("n and k must be non-negative")
46+
if k > n:
47+
return 0
48+
49+
# row[j] holds S(i, j) for the current i, updated in place from the right
50+
row = [1] + [0] * k
51+
for _ in range(n):
52+
for subsets in range(k, 0, -1):
53+
row[subsets] = subsets * row[subsets] + row[subsets - 1]
54+
row[0] = 0
55+
return row[k]
56+
57+
58+
def stirling_triangle(rows: int) -> list[list[int]]:
59+
"""
60+
Return the first ``rows`` rows (n = 0 .. rows - 1) of the triangle of Stirling
61+
numbers of the second kind, where row n lists S(n, 0) .. S(n, n).
62+
63+
>>> stirling_triangle(0)
64+
[]
65+
>>> stirling_triangle(1)
66+
[[1]]
67+
>>> stirling_triangle(5)
68+
[[1], [0, 1], [0, 1, 1], [0, 1, 3, 1], [0, 1, 7, 6, 1]]
69+
>>> stirling_triangle(-1)
70+
Traceback (most recent call last):
71+
...
72+
ValueError: rows must be non-negative
73+
"""
74+
if rows < 0:
75+
raise ValueError("rows must be non-negative")
76+
return [
77+
[stirling_number_second_kind(n, k) for k in range(n + 1)] for n in range(rows)
78+
]
79+
80+
81+
if __name__ == "__main__":
82+
import doctest
83+
84+
doctest.testmod()

0 commit comments

Comments
 (0)