Skip to content

Commit b9e1b08

Browse files
committed
Add alternative iterative solution
1 parent 1cdb854 commit b9e1b08

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

04. Recursion/04-04 Fibonacci Sequence/fibonacci.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import Optional, List
22

3-
# Recursive fuction
3+
# Recursive function
44
def fib_rec(n: int) -> int:
55
# base case
66
if n == 0 or n == 1:
@@ -41,3 +41,15 @@ def fib_iter(n: int) -> int:
4141
phi = (1 + 5 ** 0.5) / 2
4242
psi = 1 - phi
4343
return round((phi ** n - psi ** n) / 5 ** 0.5)
44+
45+
46+
def fib_iter2(n: int) -> int:
47+
# Set starting point
48+
a = 0
49+
b = 1
50+
51+
# Follow algorithm
52+
for _ in range(n):
53+
a, b = b, a + b
54+
55+
return a

0 commit comments

Comments
 (0)