Python迭代器课后题求助
本帖最后由 小莲酱biubiubiu 于 2020-4-12 02:17 编辑Python迭代器课后题求助。对迭代器进行修改,要求可以计算出闰年。我的程序到是可以跑起来,但是很奇怪的是,会重复打印4次。
各位小伙伴帮忙看看,
以下是代码:{:5_93:}
class LeapYear:
def __init__(self,year = 2020):
self.year = year
self.leapyear = 0
def __iter__(self):
return self
def __next__(self):
if ((self.year % 4 == 0) and (self.year % 100 != 0)) or (self.year % 400 == 0):
self.leapyear = self.year
self.year -= 1
if self.year < 0:
raise StopIteration
return self.leapyear
以下是结果:{:5_104:}
>>> l = LeapYear()
>>> for i in l:
if i >= 2000:
print(i)
else:
break
2020
2020
2020
2020
2016
2016
2016
2016
2012
2012
2012
2012
2008
2008
2008
2008
2004
2004
2004
2004
2000
2000
2000
2000
>>> 把-1改成-4就好啦:
class LeapYear:
def __init__(self,year = 2020):
self.year = year
self.leapyear = 0
def __iter__(self):
return self
def __next__(self):
if (self.year % 4 == 0) or ((self.year % 100 != 0) and (self.year % 400 == 0)):
self.leapyear = self.year
self.year -= 4
if self.year < 2000:
raise StopIteration
return self.leapyear
l = LeapYear()
for i in l:
print(i)
这是因为-1的话,就不符合闰年了,就会返回原来的leapyear
你还可以写一个temp,存储leapyear的值,如果temp!=leapyear
就返回leapyear。
class LeapYear:
def __init__(self,year = 2020):
self.year = year
self.leapyear = 0
self.flag = False
def __iter__(self):
return self
def __next__(self):
if (self.year % 4 == 0) or ((self.year % 100 != 0) and (self.year % 400 == 0)):
self.leapyear = self.year
self.flag = True
self.year -= 1
if self.year < 2000:
raise StopIteration
if self.flag:
self.flag = False
return self.leapyear
l = LeapYear()
for i in l:
if i:
print(i) qiuyouzhi 发表于 2020-4-12 08:07
把-1改成-4就好啦:
这是因为-1的话,就不符合闰年了,就会返回原来的leapyear
明白啦!谢谢{:5_109:} 不好意思,请问迭代器的知识点和题目在哪个章节有讲到
页:
[1]