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:
- It only prints the numbers. That reduces its usability to that particular side-effect. You cannot use the numbers for further processing.
- It builds an ever-growing list that uses up memory even though you only ever need the last two elements.
- 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.
- 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
Typeerror: Cannot Create a Consistent Method Resolution Order (Mro)
Why Doesn't Django's Model.Save() Call Full_Clean()
Python: Tf-Idf-Cosine: to Find Document Similarity
How to Avoid "Permission Denied" When Using Pip with Virtualenv
Type Annotations for *Args and **Kwargs
Matplotlib Figure Facecolor (Background Color)
How to Install a Package Inside Virtualenv
How to Set Xlim and Ylim for a Subplot in Matplotlib
Text Box with Line Wrapping in Matplotlib
How to Set Headers Using Python's Urllib
How to Add Hours to Current Time in Python
Beautifulsoup:Difference Between .Find() and .Select()
Any Reason Not to Use '+' to Concatenate Two Strings
In Python, How to Escape Newline Characters When Printing a String