[Tutor] Re: Soem list operation questions?

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Tue Dec 28 20:27:29 CET 2004


Karl Pflästerer wrote:
> Sorry but IMO the above is too much complicated for such a simple task.

That depends on your point of view, I think; I find it conceptually at 
least as easy only to think in terms of numbers when both input and 
output are numbers. Our assumptions are different too: I assume the 
input consists of digits and the output is an integer, you allow for 
bigger numbers as input and assume the output is a string.

> Either convert the digits to a string and concatenate them with:
> 
> def intlist_to_string (lst):
>     return ''.join(map(str, lst))

As Orri said, other posts already showed that approach. I just wanted to 
point out an alternative.

> 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.

Depends.

> 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

I changed it somewhat, to make it work according to my (admittely 
possibly wrong) assumptions:

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

and I used my version, without Orri's adaption to allow for non-digit 
inputs.

I also changed your function to make it return an int instead of a 
string, and ran it like:

time_it(('intlist_to_int', 'listtoint'), num=10000)

intlist_to_int(range(1,10)*10)
1.02976551489
**************************************************
listtoint(range(1,10)*10)
0.929201057676
**************************************************

Not that much difference, but mine seems to be somewhat faster in that 
case. I guess it's because yours need (after I made it return an int, 
assuming that's what kilovh wanted) to convert the string back to an 
int. The algorithm to do that looks a lot like my function.

With Orri's adaption, listtoint slows down a lot, which explains your 
results. I think different approaches are possible, and which one is 
best depends on the circumstances.

Karl Pflästerer wrote:
 > Please do *not* send copies of replies to me.
 > I read the list

I agree, but I got a copy of your reply in my inbox. Either gmane.org 
screwed up or you inadvertently cc-ed me.

-- 
"Codito ergo sum"
Roel Schroeven



More information about the Tutor mailing list