0

I have a function that checks Fibonacci numbers for even.

def fibonacci(num=4):
    fib1 = fib2 = 1
    print(0, end=' ')
    for i in range(1, num):
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')

fibonacci()

I need it to output a specified number of even numbers

Example input: 4

Example output: 0 2 8 34

3 Answers3

3

You could make your fibonacci function a generator that only yields even Fibonacci numbers, and then just pull the desired number of values from it:

def even_fibonacci():
    fib1, fib2 = 0, 1
    while True:
        if fib1 % 2 == 0:
            yield fib1
        fib1, fib2 = fib2, fib1 + fib2


it = even_fibonacci()
for _ in range(4):
    print(next(it))

prints:

0
2
8
34
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • great solution ;) love generators! – mozway Feb 12 '22 at 19:25
  • Can you explain what yields and what it does? – lostonthecoderoad Feb 12 '22 at 19:27
  • 2
    I would just swap the first line with the second and third line in the `while`. This way you can avoid thee `yield` that comes before `while`. Maybe a little more concise and elegant. Great solution. – user1984 Feb 12 '22 at 19:28
  • 1
    @lostonthecoderoad `yield` allows you to define generator functions that produce an arbitrary number of values. Instead of ending the function like `return`, a `yield` statement produces that value as the next iterator value, and then the function pauses execution until the next iteration is requested. So in this case `even_fibonacci()` returns an iterator that simply gives you the next even Fibonacci number each time you call `next()` on it. https://wiki.python.org/moin/Generators – Samwise Feb 12 '22 at 19:30
1

Use while loop instead.

def fibonacci(count=4):
    fib1 = fib2 = 1
    i = 1
    print(0, end=' ')
    while i < count:
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')
            i +=1

fibonacci()

Output: 0 2 8 34

Ka Wa Yip
  • 2,546
  • 3
  • 22
  • 35
1

You could just go over the even ones directly:

def fibonacci(num=4):
    fib1, fib2 = 1, 0
    for _ in range(num):
        print(fib2, end=' ')
        fib1, fib2 = fib1 + 2*fib2, 2*fib1 + 3*fib2

Consider two adjacent Fibonacci numbers a and b (initially 1 and 0) and what happens when you shift the window:

   a     b    # odd even
   b   a+b    # even odd
 a+b  a+2b    # odd odd
a+2b 2a+3b    # odd even

So every third Fibonacci number is even and that last line also tells you how to shift by three steps directly.

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
  • Great! How do I achieve the same level of skill? – lostonthecoderoad Feb 12 '22 at 20:20
  • 1
    @lostonthecoderoad Easy, just do a lot of stuff like this for many years :-). I knew from previous experience that there's a pattern like "every third is even", then did what I showed in the bottom half of my answer to get the details. – Kelly Bundy Feb 12 '22 at 20:31