[Tutor] Function for converting ints from base10 to base2?

Dick Moores rdm at rcblue.com
Thu Feb 22 07:25:04 CET 2007


At 09:30 PM 2/21/2007, Dick Moores wrote:
>At 06:45 PM 2/21/2007, Terry Carroll wrote:
>
>I'm glad to have learned your cool Boolean trick ( sign =
>['','-'][n<0] ), but I think instead I'll try to make
>
> >    sign = '-' if n<0 else ''
>
>a habit.

Here's some timing info:

retiming my computeBin() (the same function I first asked about--I 
just realized that running other apps, such as Firefox, while using 
timeit.py can give wildly differing results, so I've done these with 
a lot fewer running than before):

for n of 12345678901234567890
1000 loops, best of 3: 364 usec per loop

for n of 1234567890
10000 loops, best of 3: 52 usec per loop

for n of 12345
10000 loops, best of 3: 29 usec per loop



for Terry Carroll's computeBin() using   sign = ['','-'][n<0]

for n of 12345678901234567890
10000 loops, best of 3: 161 usec per loop

for n of 1234567890
10000 loops, best of 3: 76 usec per loop

for n of 12345
10000 loops, best of 3: 38 usec per loop



for Terry Carroll's computeBin() using   sign = '-' if n<0 else ''

for n of 12345678901234567890
10000 loops, best of 3: 149 usec per loop

for n of 1234567890
10000 loops, best of 3: 82 usec per loop

for n of 12345
10000 loops, best of 3: 39 usec per loop

Dick Moores




More information about the Tutor mailing list