Sobes.tech
Junior — Middle

How can you create a generator-like function in Python without using the yield statement?

sobes.tech AI

Answer from AI

An equivalent of a generator in Python without using the yield operator can be implemented using a class that implements the iterator protocol. To do this, you need to define the __iter__() and __next__() methods.

Example of a Fibonacci number generator without yield:

class Fib:
    def __init__(self, max_count):
        self.max_count = max_count
        self.count = 0
        self.a, self.b = 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.count >= self.max_count:
            raise StopIteration
        self.count += 1
        value = self.a
        self.a, self.b = self.b, self.a + self.b
        return value

# Usage:
for num in Fib(5):
    print(num)

This class behaves like a generator but without using yield. Iteration occurs through the class methods.

How can you create a generator-like function in… - sobes.tech