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

Function fib_iterative

maths/fibonacci.py:65–88  ·  view source on GitHub ↗

Calculates the first n (0-indexed) Fibonacci numbers using iteration >>> fib_iterative(0) [0] >>> fib_iterative(1) [0, 1] >>> fib_iterative(5) [0, 1, 1, 2, 3, 5] >>> fib_iterative(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (

(n: int)

Source from the content-addressed store, hash-verified

63
64
65def fib_iterative(n: int) -> list[int]:
66 """
67 Calculates the first n (0-indexed) Fibonacci numbers using iteration
68 >>> fib_iterative(0)
69 [0]
70 >>> fib_iterative(1)
71 [0, 1]
72 >>> fib_iterative(5)
73 [0, 1, 1, 2, 3, 5]
74 >>> fib_iterative(10)
75 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
76 >>> fib_iterative(-1)
77 Traceback (most recent call last):
78 ...
79 ValueError: n is negative
80 """
81 if n < 0:
82 raise ValueError("n is negative")
83 if n == 0:
84 return [0]
85 fib = [0, 1]
86 for _ in range(n - 1):
87 fib.append(fib[-1] + fib[-2])
88 return fib
89
90
91def fib_recursive(n: int) -> list[int]:

Callers

nothing calls this directly

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected