iterator - Calculating the square numbers within a range (python) -
i want able execute following code:
for in squares(5, 50): print(i) now easy implement using loop, want use iterator.
so have defined following 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 but @ moment returning none infinite amount of times. means none must because stopiteration being executed when shouldn't. think if squareroot == math.ceil(squareroot): condition correct because tested separately, can't figure out change output want. appreciated.
edit: code such as:
for in squares(4, 16): print(i) i expect output be:
4 9 16
try creating generator function:
from math import sqrt, ceil def squares(start, stop): in range(start, stop+1): sqrti = sqrt(i) if sqrti == ceil(sqrti): yield and loop it:
for in squares(4, 20): print i, which prompts:
4 9 16 edit: edited match square definition, not previous square power (sorry :p). added +1 range match question example of op.
Comments
Post a Comment