Guacaka283
Guacaka283

Reputation: 83

How to implement an infinite generator?

I am struggling to understand generators. Came across this question and need some step-by-step explanations here.

The problem is asked to create a generator function named odds. A generator object created from the generator function should produce the first count numbers when used to exhaustion in a for loop. For this question, the first odd returned should be 1.

I have trouble understanding this question, what does it mean by "a generator object created from the generator function should produce the first count numbers when used to exhaustion in a for loop.? I am also wondering why do we need count -= 1 in this function.

def odds(count):
    i = 1 
    while True:
        if i % 2:
            count -= 1
            yield i
            if not count:
                break
        i += 1

Upvotes: 0

Views: 3068

Answers (1)

martineau
martineau

Reputation: 123541

Generator functions are simply functions that yield values instead of returning them — and are thus very easy to write. i.e.:

def odds(count):
    i = 1
    for _ in range(count):
        yield i
        i += 2

for i in odds(10):
    print(i)

There's more to the difference between using the two than that. Here's a more detailed comparison: Difference between Yield and Return in Python.

Stackoverflow is not intended to replace existing tutorials or documentation, so to gain a deeper understanding of how generators work, I suggest you consult a tutorial on the topic such as: How to Use Generators and yield in Python.

Upvotes: 1

Related Questions