Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Function to test if a year is a Leap Year
- # Mike Kerry - Feb-2021 - [email protected]
- def leap_year(year):
- if year & 3:
- return False
- if not year % 400:
- return True
- return year % 100
- # Here is a copy of the above function with comments:-
- def leap_year_copy(year):
- # This bit-wise test is faster than year % 4. It examines the 2 low-order bits of the year.
- # If either a 1-bit or a 2-bit are present, then the year is not a multiple of 4. Hence not Leap.
- if year & 3:
- return False
- # If the year is divisble by 400 (i.e. there is no remainder - hence the "not"), then the year is Leap
- if not year % 400:
- return True
- # Now we know that the year is a multiple of 4, but is not a multiple of 400
- # Examine the remainder of dividing year by 100. If the remainder is zero, it is not Leap
- # If the remainder is not zero, then it is a Leap year
- # Hence in either case we can simply return the remainder,
- # which will be treated as True if there is a remainder, (e.g. year 1904)
- # and False if no remainder (e.g. year 1900)
- return year % 100
- tests = [1899, 1900, 1901, 1902, 1904, 1999, 2000, 2001, 2002,
- 2003, 2004, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
- for t in tests:
- word = ""
- if not leap_year(t):
- word = "not"
- print("The year", t, "is", word, "a leap year")
- # Output:
- #
- # The year 1899 is not a leap year
- # The year 1900 is not a leap year
- # The year 1901 is not a leap year
- # The year 1902 is not a leap year
- # The year 1904 is a leap year
- # The year 1999 is not a leap year
- # The year 2000 is a leap year
- # The year 2001 is not a leap year
- # The year 2002 is not a leap year
- # The year 2003 is not a leap year
- # The year 2004 is a leap year
- # The year 2015 is not a leap year
- # The year 2016 is a leap year
- # The year 2017 is not a leap year
- # The year 2018 is not a leap year
- # The year 2019 is not a leap year
- # The year 2020 is a leap year
- # The year 2021 is not a leap year
Add Comment
Please, Sign In to add comment