Solve a Debate
Tim Chase
python.list at tim.thechases.com
Fri Feb 15 12:10:49 EST 2008
> Ok the problem we had been asked a while back, to do a programming
> exercise (in college)
> That would tell you how many days there are in a month given a
> specific month.
>
> Ok I did my like this (just pseudo):
>
> If month = 1 or 3 or etc ....
> noDays = 31
> Elseif month = 4 or 6 etc ....
> noDays = 30
> Else
> noDays = 29
> (we didn't have to take into account a leap year)
>
> He declared an array and assigned the number of days in a month to its
> own element in an array. Now
> I realise that in this example it would not make a difference in terms
> of efficiency, but it is my belief that if
> there is more data that needed to be assigned(i.e. a couple megs of
> data) it would be simpler (and more efficient) to
> do a compare rather then assigning all that data to an array, since
> you are only going to be using 1 value and the rest
> of the data in the array is useless.
>
> What are everyone else's thoughts on this?
Well, the standard library offers its opinion:
>>> import calendar
>>> calendar.mdays
[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
>>> month = 2
>>> calendar.mdays[month]
28
If you want the actual number of days, taking leap-years into
consideration
>>> calendar.monthrange(2008,2)[1]
29
>>> calendar.monthrange(2007,2)[1]
28
So the answer is "mu"...let Python do the work for you :)
-tkc
More information about the Python-list
mailing list