i come back to python; just some questions

Max M maxm at mxm.dk
Mon Jul 15 05:14:01 EDT 2002


Duncan Booth wrote:
> ppcdev at hotmail.com (ppcdev) wrote in 

>>i was working on an old pentium II and wanted to send a very long
>>string in the USER parameter but it made my computer bug.. is it
>>normal???
>>
>>str='a'; r=range(1024);
>>for x in r[:]:
>>    str=str+str
>>
>>but it even bugs with a value of 512 and 256 for r=range(..)
> 
> You are doubling the length of the string each time, so with a range of 
> 1024 you are attempting to create a string that is 

The code should probably be expressed as::

str=''; r=range(1024);
for x in r[:]:
     str = str + 'a'

Then you only add one character at a time.

This will still create a lot if temporary strings in the process of 
building up that one string.

str = ''
str = '' + 'a'   # New string assigned to str
str = 'a' + 'a'  # New string assigned to str
str = 'aa' + 'a' # New string assigned to str
...
The second to last string will be 1023 characters long. This will give 
you an execution time that slows down with the square value of r.

A better approach is to use a list that you then join in the end. This 
is _much_ faster.

letters=[]; r=range(1024);
for x in r[:]:
     letters.append('a')
letterStr = ''.join(letters)

regards Max M




More information about the Python-list mailing list