Reputation: 1
Write a Python program to generate the next 15 leap years starting from a given year. Populate the leap years into a list and display the list. Also write the pytest test cases to test the program.
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)
when I take given year as 1684, the test case is failing, as my program prints 1700 in leap years list, but 1700 isn't a leap year.
Upvotes: 0
Views: 7971
Reputation: 1
def find_leap_years(given_year):
count = 0
leap_years = []
while count < 15:
if given_year % 400 == 0 or (given_year % 4 == 0 and given_year % 100 != 0):
leap_years.append(given_year)
count += 1
given_year +=4
else:
given_year +=1
return leap_years
leap_years_list = find_leap_years(2000)
print(leap_years_list)
Upvotes: 0
Reputation: 67
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)
Upvotes: 1
Reputation: 357
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
and
def is_leap(year):
return (year%4 == 0 and year%100 != 0) or (year % 400 == 0)
so
In [3]: find_leaps(1684)
Out[3]:
[1684,
1688,
1692,
1696,
1704,
1708,
1712,
1716,
1720,
1724,
1728,
1732,
1736,
1740,
1744]
Upvotes: 2
Reputation: 195528
I would try something simpler and utilize datetime
module. When constructing the date of 29th February fails, the exception is thrown - and we can catch it:
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)
Prints (note that 1700 isn't among the returned values):
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
Upvotes: 2