Skip to content

Commit 451c97d

Browse files
committed
docs: clean up docstring in fib_recursive function
1 parent a051ab5 commit 451c97d

File tree

1 file changed

+31
-15
lines changed

1 file changed

+31
-15
lines changed

maths/fibonacci.py

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -86,24 +86,38 @@ def fib_iterative(n: int) -> list[int]:
8686
for _ in range(n - 1):
8787
fib.append(fib[-1] + fib[-2])
8888
return fib
89-
90-
9189
def fib_recursive(n: int) -> list[int]:
9290
"""
93-
Calculates the first n (0-indexed) Fibonacci numbers using recursion
94-
>>> fib_iterative(0)
95-
[0]
96-
>>> fib_iterative(1)
97-
[0, 1]
98-
>>> fib_iterative(5)
99-
[0, 1, 1, 2, 3, 5]
100-
>>> fib_iterative(10)
101-
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
102-
>>> fib_iterative(-1)
103-
Traceback (most recent call last):
104-
...
105-
ValueError: n is negative
91+
Calculate the first n (0-indexed) Fibonacci numbers using recursion.
92+
93+
Args:
94+
n (int): The number of Fibonacci terms to generate.
95+
96+
Returns:
97+
list[int]: A list of the first n Fibonacci numbers.
98+
99+
Examples:
100+
>>> fib_recursive(0)
101+
[0]
102+
>>> fib_recursive(1)
103+
[0, 1]
104+
>>> fib_recursive(5)
105+
[0, 1, 1, 2, 3, 5]
106+
>>> fib_recursive(-1)
107+
Traceback (most recent call last):
108+
...
109+
ValueError: n is negative
106110
"""
111+
def fib_recursive_term(i: int) -> int:
112+
if i < 0:
113+
raise ValueError("n is negative")
114+
if i < 2:
115+
return i
116+
return fib_recursive_term(i - 1) + fib_recursive_term(i - 2)
117+
118+
if n < 0:
119+
raise ValueError("n is negative")
120+
return [fib_recursive_term(i) for i in range(n + 1)]
107121

108122
def fib_recursive_term(i: int) -> int:
109123
"""
@@ -112,6 +126,8 @@ def fib_recursive_term(i: int) -> int:
112126
0
113127
>>> fib_recursive_term(1)
114128
1
129+
>>> fib_recursive_term(5)
130+
115131
>>> fib_recursive_term(5)
116132
5
117133
>>> fib_recursive_term(10)

0 commit comments

Comments
 (0)