[Tutor] Leap years

Magnus Lycka magnus@thinkware.se
Mon Jan 13 08:22:01 2003


At 17:14 2003-01-12 +0000, ahimsa wrote:
>Where it falls short is on those centuries that are not leap years, such
>as 2100. Those who use Linux can get a calendar to test this: $ cal 02
>2100 , etc. Clearly, Feb 2100 only has 28 days, not the required 29.

Other and better solutions have been presented, but calendar *is* available
cross platform if you run python.

 >>> import calendar
 >>> print calendar.month(2000,2)
     February 2000
Mo Tu We Th Fr Sa Su
     1  2  3  4  5  6
  7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29

You could actually use that to implement leap(year).

 >>> def leap(year):
...     import calendar
...     return calendar.month(year, 2).find('29') != -1
...
 >>> for y in range(1990,2010):
...     print y, leap(y)
...
1990 0
1991 0
1992 1
...
2007 0
2008 1
2009 0

There is actually a flagrant bug in the implementation above.
Can you see it? How do you fix it? What other tradeoffs are
there between this and the code below?

def leap(year):
     return ((year % 100) and not (year % 4)) or not (year % 400)

Finally, for a solution that requires slightly less headache,
type...

 >>> import calendar
 >>> help(calendar)

...and look for a function whose name starts with 'i'...

Why reinvent the wheel?


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se