编写一个Python程序来生成从给定年份开始的下15个闰年。将闰年填充到列表中并显示该列表。还要编写pytest测试用例来测试程序。
def find_leap_years(given_year):
list_of_leap_years=[0]*15
# Write your logic here
if given_year%100==0 and given_year%400!=0:
for i in range(0,15):
temp=given_year+(4*(i+1))
list_of_leap_years[i]=temp
elif given_year%400==0:
for i in range(0,15):
temp=given_year+(4*i)
list_of_leap_years[i]=temp
elif given_year%4==0:
for i in range(0,15):
temp=given_year+(4*i)
list_of_leap_years[i]=temp
elif given_year%4==1:
for i in range(0,15):
temp=given_year+3+(4*i)
list_of_leap_years[i]=temp
elif given_year%4==2:
for i in range(0,15):
temp=given_year+2+(4*i)
list_of_leap_years[i]=temp
elif given_year%4==3:
for i in range(0,15):
temp=given_year+1+(4*i)
list_of_leap_years[i]=temp
return list_of_leap_years
next_leap_years=find_leap_years(1684)
print(next_leap_years)当我将给定年份设为1684年时,测试用例失败了,因为我的程序在闰年列表中打印1700,但1700不是闰年。
发布于 2019-08-07 22:06:19
我会尝试一些更简单的方法,并使用datetime模块。当构造2月29日的日期失败时,抛出异常-我们可以捕获它:
from datetime import date
def find_leap_years(year, num=15):
count = 0
while count < num:
try:
d = date(year, 2, 29)
yield year
count += 1
except ValueError:
continue
finally:
year += 1
for i, years in enumerate( find_leap_years(1690, 15), 1 ):
print(i, years)打印(注意,1700不在返回值中):
1 1692
2 1696
3 1704
4 1708
5 1712
6 1716
7 1720
8 1724
9 1728
10 1732
11 1736
12 1740
13 1744
14 1748
15 1752发布于 2019-08-07 23:11:21
def find_leaps(year, counts=15):
cnt = 0
leaps = []
while cnt != counts:
if is_leap(year):
leaps.append(year)
cnt += 1
year += 1
return leaps和
def is_leap(year):
return (year%4 == 0 and year%100 != 0) or (year % 400 == 0)所以
In [3]: find_leaps(1684)
Out[3]:
[1684,
1688,
1692,
1696,
1704,
1708,
1712,
1716,
1720,
1724,
1728,
1732,
1736,
1740,
1744]发布于 2021-02-05 20:17:41
import calendar
def Leap_Year(Test_input):
count = 0
while count < 15:
if calendar.isleap(Test_input):
print(Test_input)
count += 1
Test_input += 1
Test_input = int(input("Enter Year: "))
Leap_Year(Test_input)https://stackoverflow.com/questions/57396100
复制相似问题