Advertisement
ulfben

Leap year verification

Jan 14th, 2017
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. #! python3
  2. # -*- encoding: utf-8 -*-
  3.  
  4. #Leap year verification
  5. # Ulf Benjaminsson, 2017-01-14
  6. import sys
  7.  
  8. #(year, true if leap year)
  9. def makeTestCase(a, b):
  10.     return (a, b);
  11.  
  12. def makeTestCases():  
  13.     return [  
  14.         makeTestCase(1800, False),
  15.         makeTestCase(1900, False),
  16.         makeTestCase(2100, False),
  17.         makeTestCase(2200, False),
  18.         makeTestCase(2300, False),
  19.         makeTestCase(2500, False),
  20.         makeTestCase(1600, True),
  21.         makeTestCase(2000, True),
  22.         makeTestCase(2400, True),
  23.     ];
  24.  
  25. #In the Gregorian calendar three criteria must be taken into account to identify leap years:
  26. #The year can be evenly divided by 4;
  27. #If the year can be evenly divided by 100, it is NOT a leap year, unless;
  28. #The year is also evenly divisible by 400. Then it is a leap year.
  29. #Constraints: 1900<n<10**5
  30. def isLeapYear(year):
  31.     if(year < 1900 or year > 100000):    
  32.         raise ValueError("Bad argument: year must be 1900 < n < 10^5, was: {!s}".format(year))    
  33.     return (year % 400 == 0 or year % 100 != 0) and (year % 4 == 0);    
  34.  
  35. def main():
  36.     samples = makeTestCases();  
  37.     print('Testing for Leap Year ({:d} tests)'.format(len(samples)));    
  38.     for (year, correctAnswer) in samples:        
  39.         try:
  40.             result = isLeapYear(year);
  41.         except ValueError as error:
  42.             print(error);
  43.             continue;        
  44.         passed = result ==  correctAnswer;
  45.         print('{!s} {} = {:d} {!s}'.format(
  46.                 "Passed:" if passed else "\tFailed:", str(year), result, '.')
  47.         );
  48.         if(not passed):
  49.            print('\tShould be: {:d}'.format(correctAnswer)) ;
  50.     return 0;
  51.  
  52. if __name__ == '__main__':  
  53.     status = main();
  54.     sys.exit(status);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement