python-3.xsequence-generators

how can i iterate class objects while using generator in python?


i want to compare the 2000 pairs of a and b, and print the matching pairs and count of them.can anyone help me to get rid of it.it shows this error TypeError: 'seq_generator' object is not iterable at line 34

class generator(object):
    def __init__(self,s,start_A,fact_A):
        self.s=s
        self.start_A=start_A
        self.fact_A = fact_A
    def seq_gen_A(self):
        while self.s>0:
           self.gen_A=(self.start_A*self.fact_A)%2147483647
           self.g=self.gen_A
           self.start_A=self.gen_A
           self.bin_A=(bin(self.gen_A)[-16:])
           yield self.bin_A
           self.s=self.s-1
    def next(self):
           for i in self.seq_gen_A():
           return i
def main():
    s=200
    count=0
    a=generator(s,65,16807)
    b=generator(s,8921,48271)
    print("Matching pair")
    print("*************")
    for i in range(0,s):
        if next(a)==next(b):
           count+=1
           print(a,b)
    print('Matching pair count',count)

Solution

  • You are defining your generator not correctly. You need methods __iter__ and __next__:

    class generator(object):
        def __init__(self, s, start_A, fact_A):
            self.s = s
            self.start_A = start_A
            self.fact_A = fact_A
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if self.s <= 0:
                raise StopIteration()
            gen_A = (self.start_A*self.fact_A)%2147483647
            self.start_A = gen_A
            yield bin(gen_A)[-16:]
            self.s -= 1