forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfibonacci.py
60 lines (49 loc) · 1.53 KB
/
fibonacci.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def fibonacci(n, method="iterative"):
"""
Compute the Fibonacci number using the specified method.
Parameters:
- n (int): The nth Fibonacci number to calculate.
- method (str): The method to use ("iterative", "recursive", "memoized").
Returns:
- int: The nth Fibonacci number.
"""
if n < 0:
raise ValueError("Input must be a non-negative integer.")
# Iterative Approach (Default)
if method == "iterative":
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# Recursive Approach
elif method == "recursive":
if n == 0:
return 0
elif n == 1:
return 1
return fibonacci(n - 1, "recursive") + fibonacci(n - 2, "recursive")
# Memoized Approach
elif method == "memoized":
memo = {}
def fib_memo(n):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fib_memo(n - 1) + fib_memo(n - 2)
return memo[n]
return fib_memo(n)
else:
raise ValueError(
<<<<<<< HEAD
"Invalid method. Choose 'iterative', 'recursive', or 'memoized'."
)
=======
"Invalid method. Choose 'iterative', 'recursive', or 'memoized'."
)
>>>>>>> 7237ecd5 (Fix whitespace issue in fibonacci.py)
# Example Usage:
if __name__ == "__main__":
print(fibonacci(10)) # Default (iterative)
print(fibonacci(10, "recursive")) # Recursive method
print(fibonacci(10, "memoized")) # Memoized method