MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / fib_iterative_yield

Function fib_iterative_yield

maths/fibonacci.py:40–62  ·  view source on GitHub ↗

Calculates the first n (1-indexed) Fibonacci numbers using iteration with yield >>> list(fib_iterative_yield(0)) [0] >>> tuple(fib_iterative_yield(1)) (0, 1) >>> tuple(fib_iterative_yield(5)) (0, 1, 1, 2, 3, 5) >>> tuple(fib_iterative_yield(10)) (0, 1, 1, 2, 3, 5

(n: int)

Source from the content-addressed store, hash-verified

38
39
40def fib_iterative_yield(n: int) -> Iterator[int]:
41 """
42 Calculates the first n (1-indexed) Fibonacci numbers using iteration with yield
43 >>> list(fib_iterative_yield(0))
44 [0]
45 >>> tuple(fib_iterative_yield(1))
46 (0, 1)
47 >>> tuple(fib_iterative_yield(5))
48 (0, 1, 1, 2, 3, 5)
49 >>> tuple(fib_iterative_yield(10))
50 (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
51 >>> tuple(fib_iterative_yield(-1))
52 Traceback (most recent call last):
53 ...
54 ValueError: n is negative
55 """
56 if n < 0:
57 raise ValueError("n is negative")
58 a, b = 0, 1
59 yield a
60 for _ in range(n):
61 yield b
62 a, b = b, a + b
63
64
65def fib_iterative(n: int) -> list[int]:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected