2 views
in Python

Have a look at the following code:

for i in Squares(5, 50):

print(i)

Presently this is exceptionally simple to execute utilizing a loop, anyway I need to utilize an iterator.

So I have characterized the accompanying class:

import math

class Squares(object):

def __init__(self, start, stop):

self.start = start

self.stop = stop

def __iter__(self):

return self

def __next__(self):

start = self.start

stop = self.stop

squareroot = math.sqrt(start)

if self.start > self.stop:

raise StopIteration

if squareroot == math.ceil(squareroot):

start += 1

Be that as it may, right now this is returning None a boundless measure of times. This implies the none should be on the grounds that the StopIteration is being attempted in any event, when it shouldn't. I think me if squareroot == math.ceil(squareroot): the condition is right since I tried it independently, however, I can't sort out what to change to get the yield I need. Any assistance is valued.

For the below code:

for i in Squares(4,16):

print(i)

What I expect the output to me:

4

9

16

by (26.4k points)

Just try to create a generator function:

from math import sqrt, ceil

def Squares(start, stop):

for i in range(start, stop+1):

sqrti = sqrt(i)

if sqrti == ceil(sqrti):

yield i

Then, loop it:

for i in Squares(4, 20):

print i,

which gives:

4 9 16

Join the python online course fast, to learn python concepts in detail and get certified.

For more details, do check out the below video tutorial...