Samuel Wright
Samuel Wright

Reputation: 55

Function to list number of leap years in a list of years

I am not looking for the answer, but I am looking for a pointer in the right direction to figure this out myself.

I have a problem where I have a function to RETURN the number of leap years in a LIST of eight years. I am uncertain as to how to approach this. I have tried using a FOR LOOP and have also tried using both the calendar.isleap and calendar.leapdays methods, but I seem to be missing something because I am still getting errors.

--- code follows ---

def countLeapYears(yearList):

(student code goes here.)

print(countLeapYears([2001, 2018, 2020, 2090, 2233, 2176, 2200, 2982]))
print(countLeapYears([2001, 2018, 2020, 2092, 2204, 2176, 2200, 2982]))

I have edited and presented the question as my request got flagged On Hold for what looks like not enough information. So above is the actual question.

What I tried was this:

ly = 0
for i in yearList:
    if i % 4 == 0:
        ly += 1

Thanks.

Upvotes: 0

Views: 1592

Answers (3)

Samuel Wright
Samuel Wright

Reputation: 55

OK... thanks for the few inputs I got. With some help pushing me in the correct direction, here is what I have. It works and the answers are what I was supposed to.

import calendar

def countLeapYears(yearList):

    j=0
    for i in listYears:
        if calendar.isleap(int(i)):
            j += 1
    return j

expected output: 2

print(countLeapYears([2001, 2018, 2020, 2090, 2233, 2176, 2200, 2982]))

expected output: 4

print(countLeapYears([2001, 2018, 2020, 2092, 2204, 2176, 2200, 2982]))

Upvotes: 1

Remy
Remy

Reputation: 160

Considering your input is a list and not a range between 2 values, you are currently trying to call the wrong function.

I suggest writing your own function that takes a list as its input argument and utilizes the modulo operator within its algorithm: https://python-reference.readthedocs.io/en/latest/docs/operators/modulus.html

Upvotes: 1

JBirdVegas
JBirdVegas

Reputation: 11413

If your just looking for a pointer in the right direction here is the source code for the function your attempting to call. The doc string would might be helpful :D

def leapdays(y1, y2):
    """Return number of leap years in range [y1, y2).
       Assume y1 <= y2."""
    y1 -= 1
    y2 -= 1
    return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)

Upvotes: 0

Related Questions