You loop through every year, but you know a priori you only need to test every 4 years. You can reduce your loop overhead by a factor of 4.
To do so, first you need to "precondition" the input year so that it starts on the next (or current) leap year. You want to add 0, 3, 2, or 1, depending on whether year % 4
is 0, 1, 2, or 3. Either of the following methods will do that:
year += abs(year % -4)
year += (4 - (year % 4)) % 4
Then, in your loop, remove all instances of year+=1
as suggested by others. Instead, at the bottom of the loop, use year += 4
. Because of this, you can remove checks for year % 4 != 0
in your loop. Your algorithm would be reduced the following
def loop_year(year, leapyear_count):
year += abs(year % -4)
while leapyear_count > 0:
if year % 100 != 0 or year % 400 == 0:
print("%s is a leap year") % (year)
leapyear_count -= 1
year += 4
Of course, as suggested by others, your conditional could just be if calendar.isleap(year):
instead. However, calendar.isleap()
will check first for year % 4 == 0
, which will always be true. So from a pure performance issue (i.e., if you were generating huge list of the next N leap years), the way it is written above would be more performant.