[Tutor] Re: Soem list operation questions?

Karl Pflästerer sigurd at 12move.de
Tue Dec 28 19:43:11 CET 2004


On 28 Dez 2004, singingxduck at gmail.com wrote:

> Though, of course, by modifying your way (using str() ), it will still work:
>
>>>> def listtoint(digits):
>     result = 0
>     for digit in digits:
>         result *= (10**len(str(digit))) ## just multiply it by 10 
>         result += digit ## to the power of the number of digits
>     return result
>>>> listtoint([11,22,33,44])
> 11223344
>>>> listtoint([1,2,3,4])
> 1234

Sorry but IMO the above is too much complicated for such a simple task.
Either convert the digits to a string and concatenate them with:

def intlist_to_string (lst):
    return ''.join(map(str, lst))

or use something (suboptimal) like:

def intlist_to_string_red (lst):
    return reduce(lambda r, d: r + str(d), lst, '')

The first solution is IMO clear.  It's also the fastest solution.  If
you time the functions you will see that if intlist_to_string needs 1
second intlist_to_string_red needs 2.3 seconds and your solution
listtoint needs 3.5 seconds.

To time the functions you could use something like:

import timeit
def time_it (funs, num=1000):
    for fun in funs:
        call = '%s(range(100))' % fun
        imp = 'from __main__ import %s' % fun
        t = timeit.Timer(call, imp)
        print call
        print t.timeit(number=num)
        print '*'*50

and run it like:
.>>> time_it(('intlist_to_string', 'listtoint', 'intlist_to_string_red'), num=10000)
intlist_to_string(range(100))
1.04783373306
**************************************************
listtoint(range(100))
3.52167831386
**************************************************
intlist_to_string_red(range(100))
2.31726015457
**************************************************
.>>> 


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list



More information about the Tutor mailing list