Dijkstra on Python
Donn Cave
donn at u.washington.edu
Fri Aug 16 19:43:42 CEST 2002
Quoth Paul Rubin <phrn2002b at NOSPAMnightsong.com>:
...
 sum = ''
 for i in range(n):
 sum += f(i)

 Whoops! The second example works, but has quadratic running time!
 So real Python programs end up full of hair like

 sum = ''.join([f(i) for i in range(n)])

 which seems to me to require "decoding".

 I conclude from this that "one obvious way to do it" implies that Python
 needs a mutable (or at least extendable) string type, that supports +=
 the way list objects support appending. Maybe the above example could be:

 sum = xstr('') # xstr makes an extendable string that supports +=
 for i in range(n):
 sum += f(n)

 PEP anyone?
No, thanks! Your example was indeed enough to make one's stomach
churn with horror, but the language does not force you to use these
unreadable novelties. If it all has to fit on one line, write
sum = string.join(map(f, range(n)), '')
The conventional way to do it is
sums = []
for i in range(n):
sums.append(f(i))
sum = string.join(sums, '')
If you need an extensible string buffer, there's OOP:
sumf = StringIO()
for i in range(n):
sumf.write(f(i))
sum = sumf.getvalue()
The fact that these all work in 1.5.2 the same as they do in 2.2
is not a mark against them.
Donn Cave, donn at u.washington.edu
More information about the Pythonlist
mailing list