Skip to content

Commit

Permalink
issue TheAlgorithms#10837 Move fib_recursive_term() outside of fib_re…
Browse files Browse the repository at this point in the history
…cursive() for proper doctest coverage and improved code organization.
  • Loading branch information
MannCode committed Feb 25, 2024
1 parent c6ca194 commit 7a4d2bb
Showing 1 changed file with 21 additions and 22 deletions.
43 changes: 21 additions & 22 deletions maths/fibonacci.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,27 @@ def fib_iterative(n: int) -> list[int]:
fib.append(fib[-1] + fib[-2])
return fib

def fib_recursive_term(i: int) -> int:
"""
Calculates the i-th (0-indexed) Fibonacci number using recursion
>>> fib_recursive_term(0)
0
>>> fib_recursive_term(1)
1
>>> fib_recursive_term(5)
5
>>> fib_recursive_term(10)
55
>>> fib_recursive_term(-1)
Traceback (most recent call last):
...
Exception: n is negative
"""
if i < 0:
raise ValueError("n is negative")
if i < 2:
return i
return fib_recursive_term(i - 1) + fib_recursive_term(i - 2)

def fib_recursive(n: int) -> list[int]:
"""
Expand All @@ -100,28 +121,6 @@ def fib_recursive(n: int) -> list[int]:
ValueError: n is negative
"""

def fib_recursive_term(i: int) -> int:
"""
Calculates the i-th (0-indexed) Fibonacci number using recursion
>>> fib_recursive_term(0)
0
>>> fib_recursive_term(1)
1
>>> fib_recursive_term(5)
5
>>> fib_recursive_term(10)
55
>>> fib_recursive_term(-1)
Traceback (most recent call last):
...
Exception: n is negative
"""
if i < 0:
raise ValueError("n is negative")
if i < 2:
return i
return fib_recursive_term(i - 1) + fib_recursive_term(i - 2)

if n < 0:
raise ValueError("n is negative")
return [fib_recursive_term(i) for i in range(n + 1)]
Expand Down

0 comments on commit 7a4d2bb

Please sign in to comment.