acclivity

pyLeapYearTest

Feb 23rd, 2021 (edited)
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. #  Function to test if a year is a Leap Year
  2. #  Mike Kerry - Feb-2021 - [email protected]
  3.  
  4.  
  5. def leap_year(year):
  6.     if year & 3:
  7.         return False
  8.     if not year % 400:
  9.         return True
  10.     return year % 100
  11.  
  12.  
  13. # Here is a copy of the above function with comments:-
  14. def leap_year_copy(year):
  15.     # This bit-wise test is faster than year % 4. It examines the 2 low-order bits of the year.
  16.     # If either a 1-bit or a 2-bit are present, then the year is not a multiple of 4. Hence not Leap.
  17.     if year & 3:
  18.         return False
  19.  
  20.     # If the year is divisble by 400 (i.e. there is no remainder - hence the "not"), then the year is Leap
  21.     if not year % 400:
  22.         return True
  23.  
  24.     # Now we know that the year is a multiple of 4, but is not a multiple of 400
  25.  
  26.     # Examine the remainder of dividing year by 100. If the remainder is zero, it is not Leap
  27.     # If the remainder is not zero, then it is a Leap year
  28.     # Hence in either case we can simply return the remainder,
  29.     # which will be treated as True if there is a remainder, (e.g. year 1904)
  30.     # and False if no remainder (e.g. year 1900)
  31.     return year % 100
  32.  
  33.  
  34. tests = [1899, 1900, 1901, 1902, 1904, 1999, 2000, 2001, 2002,
  35.          2003, 2004, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
  36.  
  37. for t in tests:
  38.     word = ""
  39.     if not leap_year(t):
  40.         word = "not"
  41.     print("The year", t, "is", word, "a leap year")
  42.  
  43.  
  44. # Output:
  45. #
  46. # The year 1899 is not a leap year
  47. # The year 1900 is not a leap year
  48. # The year 1901 is not a leap year
  49. # The year 1902 is not a leap year
  50. # The year 1904 is  a leap year
  51. # The year 1999 is not a leap year
  52. # The year 2000 is  a leap year
  53. # The year 2001 is not a leap year
  54. # The year 2002 is not a leap year
  55. # The year 2003 is not a leap year
  56. # The year 2004 is  a leap year
  57. # The year 2015 is not a leap year
  58. # The year 2016 is  a leap year
  59. # The year 2017 is not a leap year
  60. # The year 2018 is not a leap year
  61. # The year 2019 is not a leap year
  62. # The year 2020 is  a leap year
  63. # The year 2021 is not a leap year
  64.  
Add Comment
Please, Sign In to add comment