Fibonacci from a generator

Produce the Fibonacci numbers one at a time.

What to build

A generator that remembers two values between calls.

Requirements

  • Complete fib() so that it yields 0, 1, 1, 2, 3, 5 and so on, forever.
  • Leave the rest of the program as it is. It prints the first n values.

Input

One whole number n.

Output

n numbers separated by spaces.

Constraints

n is from 1 to 90.

Example

Input:

6

Output:

0 1 1 2 3 5

Why it works

A generator's variables survive between values, so it needs only the last two numbers, however far along the sequence it goes.

Examples

Example 1 · Input
6
Expected output
0 1 1 2 3 5
Example 2 · Input
1
Expected output
0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep two values, a and b, starting at 0 and 1.

Hint 2

yield a, then move along with a, b = b, a + b.

Solution

Show one correct solution (try it yourself first)
import itertools

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

n = int(input())
print(" ".join(str(x) for x in itertools.islice(fib(), n)))

Lesson: Generators →