O(n^2) is bad - can it be fixed?

Delaney, Timothy tdelaney at avaya.com
Tue May 22 02:18:21 EDT 2001


> Another method would be to use the array built-in module. 
> This will probably
> save memory over the list version, and is almost the 
> equivalent of the Java
> StringBuffer, except it's so much more ;) Testing both of 
> these though,
> using a list was *much* faster than using an array.

Oops - this is misleading. I stupidly did this test incorrectly - I changed
the function to use a try/except to allow it to use strings, lists and
arrays ...

try:
    listorstring += ' '
except:
    listorstring.append(' ')

Now, who wants to point out the flaw of comparing using a list (which has
.append() as well as direct concatenation), and using an array (which only
has .append()) ...

Yep, I was taking the overhead of throwing an exception on the array test.

When I changed it around

try:
    listorstring.append(' ')
except:
    listorstring += ' '

lists and arrays ran pretty close to the same (I didn't do any formal
timing).

Bah! Get the algorithm right!

Tim Delaney




More information about the Python-list mailing list