Fibonacci Sequence Practice Problem
This data science coding problem helps you practice Control Flow & Loops, fibonacci sequence, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Control Flow & Loops.
- Problem ID: 76
- Problem key: 76-fibonacci-sequence
- URL: https://datacrack.app/solve/76-fibonacci-sequence
- Difficulty: easy
- Topic: Control Flow & Loops
- Module: Python Fundamentals
Problem Statement
# 🧩 Fibonacci Sequence
---
### 🎯 Goal
The Fibonacci sequence is one of the most frequently asked problems in coding interviews. It builds intuition for **loop-based accumulation** — a pattern that appears in time-series forecasting, dynamic programming, and sequence modeling.
---
### 🔍 The Fibonacci Rule
$$
F(0) = 0, \quad F(1) = 1, \quad F(n) = F(n-1) + F(n-2)
$$
Each number is the **sum of the two preceding numbers**:
```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
```
---
### 💻 Task
Implement `fibonacci(n)` **iteratively** (using a loop, not recursion).
---
### 📥 Input
- `n`: int — the number of Fibonacci numbers to generate (starting from F(0))
### 📤 Output
- A list of the first `n` Fibonacci numbers
---
### 🧩 Starter Code
```python
def fibonacci(n):
"""
Generate the first n Fibonacci numbers iteratively.
Args:
n (int): How many Fibonacci numbers to generate
Returns:
list[int]: First n Fibonacci numbers starting from 0
"""
# 🧠 TODO: Handle edge cases (n=1 returns [0], n=2 returns [0, 1])
# 🧠 TODO: Loop from index 2 to n, compute each number from the previous two
pass
```
---
### 💡 Example
```python
fibonacci(8)
# Expected: [0, 1, 1, 2, 3, 5, 8, 13]
fibonacci(1)
# Expected: [0]
```
---
### 🔑 Key Concepts
- Seed the list with `[0, 1]` before entering the loop
- Access last two elements: `result[-1]` and `result[-2]`
- Handle `n == 1` separately (only `[0]`)Starter Code
def fibonacci(n):
"""
Generate the first n Fibonacci numbers iteratively.
Args:
n (int): How many Fibonacci numbers to generate
Returns:
list[int]: First n Fibonacci numbers starting from 0
"""
# 🧠 TODO: Handle edge cases (n=1 returns [0], n=2 returns [0, 1])
# 🧠 TODO: Loop from index 2 to n, compute each number from the previous two
pass