Skip to content

Commit 2fa555b

Browse files
committed
add a yiled method to fibonaci
1 parent 5645084 commit 2fa555b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

maths/fibonacci.py

+21
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import functools
2020
from math import sqrt
2121
from time import time
22+
from collections.abc import Generator
2223

2324

2425
def time_func(func, *args, **kwargs):
@@ -60,6 +61,22 @@ def fib_iterative(n: int) -> list[int]:
6061
fib.append(fib[-1] + fib[-2])
6162
return fib
6263

64+
def fib_iterative_yield(n: int) -> Generator[int]:
65+
"""
66+
Calculates the first n (1-indexed) Fibonacci numbers using iteration with yield method to save memory
67+
>>> f = fib_iterative_yield(3)
68+
>>> next(f)
69+
1
70+
>>> next(f)
71+
1
72+
>>> next(f)
73+
2
74+
"""
75+
a, b = 0, 1
76+
for _ in range(n):
77+
yield b
78+
a, b = b, a + b
79+
6380

6481
def fib_recursive(n: int) -> list[int]:
6582
"""
@@ -196,10 +213,14 @@ def fib_binet(n: int) -> list[int]:
196213
return [round(phi**i / sqrt_5) for i in range(n + 1)]
197214

198215

216+
217+
199218
if __name__ == "__main__":
200219
num = 30
201220
time_func(fib_iterative, num)
202221
time_func(fib_recursive, num) # Around 3s runtime
203222
time_func(fib_recursive_cached, num) # Around 0ms runtime
204223
time_func(fib_memoization, num)
205224
time_func(fib_binet, num)
225+
time_func(fib_iterative_yield, num)
226+

0 commit comments

Comments
 (0)