|
| 1 | +""" |
| 2 | +Bell numbers represent the number of ways to partition a set into non-empty |
| 3 | +subsets. This module provides functions to calculate Bell numbers for sets of |
| 4 | +integers. In other words, the first (n + 1) Bell numbers. |
| 5 | +
|
| 6 | +For more information about Bell numbers, refer to: |
| 7 | +https://en.wikipedia.org/wiki/Bell_number |
| 8 | +""" |
| 9 | + |
| 10 | + |
| 11 | +def bell_numbers(max_set_length: int) -> list[int]: |
| 12 | + """ |
| 13 | + Calculate Bell numbers for the sets of lengths from 0 to max_set_length. |
| 14 | + In other words, calculate first (max_set_length + 1) Bell numbers. |
| 15 | +
|
| 16 | + Args: |
| 17 | + max_set_length (int): The maximum length of the sets for which |
| 18 | + Bell numbers are calculated. |
| 19 | +
|
| 20 | + Returns: |
| 21 | + list: A list of Bell numbers for sets of lengths from 0 to max_set_length. |
| 22 | +
|
| 23 | + Examples: |
| 24 | + >>> bell_numbers(0) |
| 25 | + [1] |
| 26 | + >>> bell_numbers(1) |
| 27 | + [1, 1] |
| 28 | + >>> bell_numbers(5) |
| 29 | + [1, 1, 2, 5, 15, 52] |
| 30 | + """ |
| 31 | + if max_set_length < 0: |
| 32 | + raise ValueError("max_set_length must be non-negative") |
| 33 | + |
| 34 | + bell = [0] * (max_set_length + 1) |
| 35 | + bell[0] = 1 |
| 36 | + |
| 37 | + for i in range(1, max_set_length + 1): |
| 38 | + for j in range(i): |
| 39 | + bell[i] += _binomial_coefficient(i - 1, j) * bell[j] |
| 40 | + |
| 41 | + return bell |
| 42 | + |
| 43 | + |
| 44 | +def _binomial_coefficient(total_elements: int, elements_to_choose: int) -> int: |
| 45 | + """ |
| 46 | + Calculate the binomial coefficient C(total_elements, elements_to_choose) |
| 47 | +
|
| 48 | + Args: |
| 49 | + total_elements (int): The total number of elements. |
| 50 | + elements_to_choose (int): The number of elements to choose. |
| 51 | +
|
| 52 | + Returns: |
| 53 | + int: The binomial coefficient C(total_elements, elements_to_choose). |
| 54 | +
|
| 55 | + Examples: |
| 56 | + >>> _binomial_coefficient(5, 2) |
| 57 | + 10 |
| 58 | + >>> _binomial_coefficient(6, 3) |
| 59 | + 20 |
| 60 | + """ |
| 61 | + if elements_to_choose in {0, total_elements}: |
| 62 | + return 1 |
| 63 | + |
| 64 | + if elements_to_choose > total_elements - elements_to_choose: |
| 65 | + elements_to_choose = total_elements - elements_to_choose |
| 66 | + |
| 67 | + coefficient = 1 |
| 68 | + for i in range(elements_to_choose): |
| 69 | + coefficient *= total_elements - i |
| 70 | + coefficient //= i + 1 |
| 71 | + |
| 72 | + return coefficient |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + import doctest |
| 77 | + |
| 78 | + doctest.testmod() |
0 commit comments