Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions fibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
def fibonacci(n):
"""Return the n-th term of the Fibonacci sequence (0-indexed)."""
if n < 0:
raise ValueError("n must be a non-negative integer")
if n == 0:
return 0

a, b = 0, 1
for _ in range(n - 1):
Comment on lines +8 to +9

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Off-by-one error in the loop bound. With the accumulator initialized to a, b = 0, 1, producing fib(n) needs n iterations, but range(n - 1) runs one too few. As written the function returns fib(n-1) for all n >= 1: fibonacci(1) yields 0 (should be 1), fibonacci(9) yields 21 (should be 34). The n == 0 early return already covers the zero case, so the loop count should simply be n.

Suggested change
a, b = 0, 1
for _ in range(n - 1):
for _ in range(n):

a, b = b, a + b
return a


if __name__ == "__main__":
for i in range(10):
print(f"fibonacci({i}) = {fibonacci(i)}")