Python Fibonacci Generator

infinite Fibonacci generator in python with yield error?

Each call to fib_gen() creates a new generator that is in initial state. Try assigning the return value of fib_gen() to a variable and calling next() on that same variable.

How can I improve my fibonacci sequence generator?

Yours has some disadvantages:

  1. It only prints the numbers. That reduces its usability to that particular side-effect. You cannot use the numbers for further processing.
  2. It builds an ever-growing list that uses up memory even though you only ever need the last two elements.
  3. You have hard-coded the number of fibonacci numbers you want to generate. You have to change the generation code if you need more of them.
  4. It is not encapsulated in a function. That reduces its reusability.

Issues 1. and 3. also apply to the first alternative you proposed.

The parametrized generator function (second proposed alternative)

def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

does not have any of those problems. If you want to print some numbers, you can easily do that (see how the purpose and count are left to the caller):

for f in fib(5):
print(f)

or you can collect them in a list if you need to:

fib_nums = list(fib(5))

or apply a function to all of them:

for double_fib in map((2).__mul__, fib(5)):
print(double_fib)

And if you need the numbers with their according index, there are built-in utils you can apply:

for i, f in enumerate(fib(5)):
print(f"{i}: {f}")


Related Topics



Leave a reply



Submit