Fibonacci Sequence via Loop

Medium ⏱ 12 min 61% acceptance ★★★★☆ 4.2
Write a function fibonacci(n) that returns a list containing the first n Fibonacci numbers (starting 0, 1, 1, 2, 3, ...), computed iteratively with a loop (no recursion).

Examples

Example 1
Input
fibonacci(6)
Output
[0, 1, 1, 2, 3, 5]
Explanation

First six Fibonacci numbers.

Example 2
Input
fibonacci(1)
Output
[0]
Explanation

Just the first term.

Constraints

  • n is a positive integer.
  • Must use iteration, not recursion.

Topics

Loopsfor loopaccumulator

Companies

MetaLinkedIn

Hints

Hint 1

Keep two running variables for the previous two terms and update them each iteration.

Hint 2

Handle n == 1 as a special case that returns just [0].

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.