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

Function fib_recursive

maths/fibonacci.py:91–132  ·  view source on GitHub ↗

Calculates the first n (0-indexed) Fibonacci numbers using recursion >>> fib_recursive(0) [0] >>> fib_recursive(1) [0, 1] >>> fib_recursive(5) [0, 1, 1, 2, 3, 5] >>> fib_recursive(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_recursive(-1) Traceback (

(n: int)

Source from the content-addressed store, hash-verified

89
90
91def fib_recursive(n: int) -> list[int]:
92 """
93 Calculates the first n (0-indexed) Fibonacci numbers using recursion
94 >>> fib_recursive(0)
95 [0]
96 >>> fib_recursive(1)
97 [0, 1]
98 >>> fib_recursive(5)
99 [0, 1, 1, 2, 3, 5]
100 >>> fib_recursive(10)
101 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
102 >>> fib_recursive(-1)
103 Traceback (most recent call last):
104 ...
105 ValueError: n is negative
106 """
107
108 def fib_recursive_term(i: int) -> int:
109 """
110 Calculates the i-th (0-indexed) Fibonacci number using recursion
111 >>> fib_recursive_term(0)
112 0
113 >>> fib_recursive_term(1)
114 1
115 >>> fib_recursive_term(5)
116 5
117 >>> fib_recursive_term(10)
118 55
119 >>> fib_recursive_term(-1)
120 Traceback (most recent call last):
121 ...
122 ValueError: n is negative
123 """
124 if i < 0:
125 raise ValueError("n is negative")
126 if i < 2:
127 return i
128 return fib_recursive_term(i - 1) + fib_recursive_term(i - 2)
129
130 if n < 0:
131 raise ValueError("n is negative")
132 return [fib_recursive_term(i) for i in range(n + 1)]
133
134
135def fib_recursive_cached(n: int) -> list[int]:

Callers

nothing calls this directly

Calls 1

fib_recursive_termFunction · 0.85

Tested by

no test coverage detected