MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / catalan_numbers

Function catalan_numbers

dynamic_programming/catalan_numbers.py:30–57  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

28
29
30def 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
60if __name__ == "__main__":

Callers 1

catalan_numbers.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected