Solve a Debate

Ivan Van Laningham ivanlan9 at gmail.com
Fri Feb 15 13:05:02 EST 2008


Hi All--
Lookup tables are always significantly faster than a bunch of ifs.

Metta,
Ivan

On Fri, Feb 15, 2008 at 10:10 AM, Tim Chase
<python.list at tim.thechases.com> wrote:
> > 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
>
>
>
>
>
>
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>



-- 
Ivan Van Laningham
God N Locomotive Works
http://www.pauahtun.org/
http://www.python.org/workshops/1998-11/proceedings/papers/laningham/laningham.html
Army Signal Corps: Cu Chi, Class of '70
Author: Teach Yourself Python in 24 Hours



More information about the Python-list mailing list