Search code examples
pythongenerator

How to create a leap year generator in python 3


I am trying to create a leap year generator with start, stop, and step that will calculate the number of leap years, sum of leap years, number of leap years divisible by 3, and the sum of leap years divisible by 3. I tried writing this code, but I don't think my answers are right because I keep getting the wrong number of years within the designated range.

def leap(start,stop,step=1):
    import calendar
    l=[]
    
    for i in range(start, stop+1,step):
        if i % 4 == 0:
            if i % 100 ==0:
                if i % 400 ==0:
                    l.append(i)
                else:
                    l.append(i)
    return l

l = leap(1901,2000,1)

print("number of leap years:",len(l))
print("sum of leap years:",sum(l))

c=0
s=0

for i in l:
    if i%3==0:
        c=c+1
        s=s+i  
print("leap years divisible by 3:",c)
print("sum of divisible leap years:",s)

I don't think Python is treating the l = leap(1901,2000,1) part as a range. What could I be doing wrong?


Solution

  • Importing calendar then use .isleap()?

    def leap(start,stop,step=1):
        import calendar
        return [i for i in range(start,stop+1,step) if calendar.isleap(i)]
    
    l = leap(1901,2000,1)
    

    And if you want to use corrected condition:

    def leap(start,stop,step=1):
        return [i for i in range(start,stop+1,step) if i % 4 == 0 and (i % 100 != 0 or i % 400 == 0)]
    
    l = leap(1901,2000,1)