Leap Year
A year is a leap year if it is divisible by 4, except years divisible by 100, which are not leap years, except years divisible by 400, which are.
Write is_leap_year(year) that returns True or False.
Understand the problem
Apply the rule by hand before you code it.
Is 1900 a leap year?
- Yes, it is divisible by 4
- No, it is divisible by 100 but not by 400
- Yes, it is divisible by 100
1900 is divisible by 4, but it is a century year (divisible by 100) and not divisible by 400, so the exception applies. 1900 is not a leap year.
Is 2000 a leap year?
- Yes
- No
2000 is a century year, but it is divisible by 400, so the exception to the exception applies. It is a leap year.
How many leap years are there from 1996 to 2004, including both ends?
The leap years are 1996, 2000 and 2004. 2000 counts because it is divisible by 400. 1997, 1998, 1999, 2001, 2002 and 2003 are not divisible by 4.
Write the solution
The tests include century years, because that is where simple versions go wrong.
def is_leap_year(year):
# Write your code here.
pass
Hint 1: a question to ask yourself
Which rule is the most specific one? In what order must the checks be made so the specific rule is not hidden by a general one?
Hint 2: the shape of the answer
One boolean expression: divisible by 4, and (not divisible by 100, or divisible by 400). Use % to test divisibility.
Reflect
Solution
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Another way: one rule per line, most specific first
def is_leap_year(year):
if year % 400 == 0:
return True
if year % 100 == 0:
return False
return year % 4 == 0
Another way: the standard library
import calendar
def is_leap_year(year):
return calendar.isleap(year)
What this tests: turning a rule with exceptions into code, and boolean logic with and, or and %.
Pattern: put the most specific rule first, or write the rule as one expression. The one-line version is correct for every year. The rule-per-line version reads like the description and is easier to extend. Both avoid the classic mistake of stopping at "divisible by 4".
Cost: a few arithmetic operations, O(1).
What an interviewer might ask next: How would you test this function? (Years on both sides of each rule: 1899, 1900, 1901, 1999, 2000, 2001, 2004.)
VISIBLE = 3
CASES = [
((2024,), True, 'a normal leap year'),
((2023,), False, 'a normal year'),
((1900,), False, 'a century that is not a leap year'),
((2000,), True, 'a century that is a leap year'),
((2100,), False, 'the next century'),
((2400,), True, 'divisible by 400'),
((1996,), True, 'divisible by 4'),
((1,), False, 'year one'),
((4,), True, 'year four'),
((1800,), False, 'another century'),
]