Return a list of the Catalan number sequence from 0 through `upper_limit`. >>> catalan_numbers(5) [1, 1, 2, 5, 14, 42] >>> catalan_numbers(2) [1, 1, 2] >>> catalan_numbers(-1) Traceback (most recent call last): ValueError: Limit for the Catalan sequence must be ≥ 0
(upper_limit: int)
| 28 | |
| 29 | |
| 30 | def catalan_numbers(upper_limit: int) -> "list[int]": |
| 31 | """ |
| 32 | Return a list of the Catalan number sequence from 0 through `upper_limit`. |
| 33 | |
| 34 | >>> catalan_numbers(5) |
| 35 | [1, 1, 2, 5, 14, 42] |
| 36 | >>> catalan_numbers(2) |
| 37 | [1, 1, 2] |
| 38 | >>> catalan_numbers(-1) |
| 39 | Traceback (most recent call last): |
| 40 | ValueError: Limit for the Catalan sequence must be ≥ 0 |
| 41 | """ |
| 42 | if upper_limit < 0: |
| 43 | raise ValueError("Limit for the Catalan sequence must be ≥ 0") |
| 44 | |
| 45 | catalan_list = [0] * (upper_limit + 1) |
| 46 | |
| 47 | # Base case: C(0) = C(1) = 1 |
| 48 | catalan_list[0] = 1 |
| 49 | if upper_limit > 0: |
| 50 | catalan_list[1] = 1 |
| 51 | |
| 52 | # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i |
| 53 | for i in range(2, upper_limit + 1): |
| 54 | for j in range(i): |
| 55 | catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] |
| 56 | |
| 57 | return catalan_list |
| 58 | |
| 59 | |
| 60 | if __name__ == "__main__": |