0

I went through Beginning Python fibonacci generator

How to write with out stop number where we want to stop.

My Code of FIbnocci is below

def Fibonnaci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    else:
        return (Fibonnaci(n-1)+ Fibonnaci(n-2))

n = int(input())
print(Fibonnaci(n))

I wrote with yield statement but its infinite loop running

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

fib(7)

Desired out > 13

3 Answers3

1

You don't want to loop infinitely; you need to keep track of how many times you've performed an operation.

Hold the state of a counter in your loop while you generate elements. Keep going until count >= n.

def fib(n):
     count = 0
     a, b = 0, 1
     while count < n:
             yield a
             a, b = b, a + b
             count += 1

You can then leverage this in a list comprehension to get all of the values up to that Fibonacci number if you so desire.

[i for i in fib(10)]
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • You can also use `for _ in range(n):` getting rid of the `count` var. `list(fib(10))` from the caller is an alternative to the list comp. – ggorlen Aug 19 '19 at 03:41
  • @ggorlen: This is more meant to be illustrative of the kind of state that needs to be held. I'm sure this could be done in a different way but I don't think that the way you're describing it would make it more readable. – Makoto Aug 19 '19 at 03:42
0

The yield statement is used to iterate over some data, yielding one value at a time.

So: iterate over it

f = fib()
fibs = [next(f) for _ in range(7)]
fib_7 = fibs[-1]

note as you start with yield a you get a 0 as first number. so shift to yield b which will work as expected

ted
  • 13,596
  • 9
  • 65
  • 107
0
n = int(input())
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b  #swap the values, sum

def firstn(g, n):
    for i in range(n):
        yield g.__next__() # take  the next value for the generator


t =  (list(firstn(fibonacci(), n+1))) # Put in a list
print (t[-1])   #take the last element