我希望能够执行以下代码:
for i in Squares(5, 50):
print(i)
Run Code Online (Sandbox Code Playgroud)
现在使用循环很容易实现,但是我想使用迭代器.
所以我定义了以下类:
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
Run Code Online (Sandbox Code Playgroud)
但目前这种情况None无数次返回.这意味着必须是因为StopIteration即使它不应该执行也是如此.我认为我的if squareroot == math.ceil(squareroot):情况是正确的,因为我单独测试它,但我无法弄清楚要改变什么来获得我想要的输出.任何帮助表示赞赏.
编辑:对于如下代码:
for i in Squares(4, 16):
print(i)
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
4
9
16
Run Code Online (Sandbox Code Playgroud)
尝试创建一个生成器函数:
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
Run Code Online (Sandbox Code Playgroud)
然后循环它:
for i in Squares(4, 20):
print i,
Run Code Online (Sandbox Code Playgroud)
提示:
4 9 16
Run Code Online (Sandbox Code Playgroud)
编辑:编辑以匹配平方定义,而不是之前的平方幂(抱歉:P)。在范围中添加了 +1 以匹配 OP 的问题示例。