-3

So i have created a function which will essentially take a value as a parameter and run the fibonacci sequence. It tends to only print 1 each time i am using next. I am not sure why it is doing this. When it reached the yield keyword it returns back the value of 1. So far my code is as follows :

def fibonacci(n):
    curr = 1
    prev = 0
    counter = 0
    while counter < n:
        yield curr
        prev, curr = curr, prev + curr
        counter += 1


print(next(fibonacci(10)))
print(next(fibonacci(10)))
print(next(fibonacci(10)))
  • 3
    Please search the net before asking the questions that have been already answered. [Python Fibonacci Generator](https://stackoverflow.com/questions/3953749/python-fibonacci-generator) – Vinay Bharadhwaj Jan 23 '19 at 15:24
  • 5
    Possible duplicate of [Python Fibonacci Generator](https://stackoverflow.com/questions/3953749/python-fibonacci-generator) – Vinay Bharadhwaj Jan 23 '19 at 15:25
  • 1
    With each call to `fibonacci(10)` you create a new generator/iterator which begins again with 1. – Michael Butscher Jan 23 '19 at 15:30

2 Answers2

1

You need to instantiate object of your generator before using it, for example:

g = fibonacci(10)

print(next(g))
print(next(g))
print(next(g))

will return following output:

1
1
2
nkovacevic
  • 106
  • 4
0

Here is one solution that works for me:

def fibonacci(n):
    fibonacci_list = []
    curr = 1
    prev = 0
    counter = 0
    while counter < n:
        prev, curr = curr, prev + curr
        counter += 1
        fibonacci_list.append(curr)

    return fibonacci_list;


x = fibonacci(10)
print(x)

Tell me if it helped

SLP

SLP
  • 303
  • 2
  • 14