- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathbell_numbers.py
81 lines (61 loc) · 2.14 KB
/
bell_numbers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
Bell numbers represent the number of ways to partition a set into non-empty
subsets. This module provides functions to calculate Bell numbers for sets of
integers. In other words, the first (n + 1) Bell numbers.
For more information about Bell numbers, refer to:
https://en.wikipedia.org/wiki/Bell_number
"""
defbell_numbers(max_set_length: int) ->list[int]:
"""
Calculate Bell numbers for the sets of lengths from 0 to max_set_length.
In other words, calculate first (max_set_length + 1) Bell numbers.
Args:
max_set_length (int): The maximum length of the sets for which
Bell numbers are calculated.
Returns:
list: A list of Bell numbers for sets of lengths from 0 to max_set_length.
Examples:
>>> bell_numbers(-2)
Traceback (most recent call last):
...
ValueError: max_set_length must be non-negative
>>> bell_numbers(0)
[1]
>>> bell_numbers(1)
[1, 1]
>>> bell_numbers(5)
[1, 1, 2, 5, 15, 52]
"""
ifmax_set_length<0:
raiseValueError("max_set_length must be non-negative")
bell= [0] * (max_set_length+1)
bell[0] =1
foriinrange(1, max_set_length+1):
forjinrange(i):
bell[i] +=_binomial_coefficient(i-1, j) *bell[j]
returnbell
def_binomial_coefficient(total_elements: int, elements_to_choose: int) ->int:
"""
Calculate the binomial coefficient C(total_elements, elements_to_choose)
Args:
total_elements (int): The total number of elements.
elements_to_choose (int): The number of elements to choose.
Returns:
int: The binomial coefficient C(total_elements, elements_to_choose).
Examples:
>>> _binomial_coefficient(5, 2)
10
>>> _binomial_coefficient(6, 3)
20
"""
ifelements_to_choosein {0, total_elements}:
return1
elements_to_choose=min(elements_to_choose, total_elements-elements_to_choose)
coefficient=1
foriinrange(elements_to_choose):
coefficient*=total_elements-i
coefficient//=i+1
returncoefficient
if__name__=="__main__":
importdoctest
doctest.testmod()