My question is about generator. For loop can iterate automatically but still why here we incremented with additional step?

Question:

In Generator, why do we need this additional step in this program? Could you explain this in detail?

    class PrimeGenerator:

       def __init__(self, stop):
       self.stop = stop
       self.start=2
       self.number=0


       def __next__(self):
           for self.number in range(self.start,self.stop):
                for x in range(2, self.number):
                      if self.number % x == 0:
                      break
                else:
                   self.start=self.number+1
                   return self.number
             raise StopIteration                   


  obj = PrimeGenerator(5)
  print(next(obj))

In the above code why here we increment the self.start value? That is self.start=self.number+1. My doubt is it can automatically iterate through for loop. Still why here again incremented?

Asked By: Madhumathi

||

Answers:

The Generator is supposed to generate prime numbers. It starts with value 2 as self.number and then tests if any number from 2 to self.number divides self.number, if this is the case, it is no prime number (as prime numbers can only be divided by 1 or themselfes).

After it found a prime number (which means it did not go to the break statement, as no number divided it) you have to increment the self.start, to start one number after the prime number you found right now. Then you return the prime.

If you would not increment the self.start, then you would always test for the first prime number.

Additional:
Your test only tests for prime numbers greater than 2 as 2 % 2 equals zero.

And for future posts please (especially for python code) be sure to make your tabs correctly. Your code should look like this:

class PrimeGenerator:

  def __init__(self, stop):
    self.stop = stop
    self.start=2
    self.number=0

  def __next__(self):
    for self.number in range(self.start,self.stop):
      for x in range(2, self.number):
        if self.number % x == 0:
          break
      else:
        self.start=self.number+1
        return self.number                 


obj = PrimeGenerator(7)
print(next(obj))
Answered By: Spanching
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.