Dumb python questions

Alex Martelli aleaxit at yahoo.com
Wed Aug 15 15:10:04 CEST 2001


"Paul Rubin" <phr-n2001 at nightsong.com> wrote in message
news:7xofphd4ql.fsf at ruckus.brouhaha.com...
    ...
> xrange apparently doesn't malloc the values until they're used, but
> they eventually get malloc'd.

One at a time, sure, just like in the loop you outline below.

> I think functional programming has run
> slightly amuck here.  What's wanted is something equivalent to
>
>    sum = 0
>    i = 1
>    while i <= 100 :
>       sum = sum + i
>       i = i + 1

import operator
sum = reduce(operator.add, xrange(101))

IS "something equivalent" to the loop you've outlined, except for
the little detail that it's faster.

Easy to measure -- take this script:

import time

start = time.clock()
for x in range(1000):
    sum = 0
    i = 1
    while i <= 100 :
        sum = sum + i
        i = i + 1
stend = time.clock()
print stend-start

start = time.clock()
for x in range(1000):
    import operator
    sum = reduce(operator.add, xrange(101))
stend = time.clock()
print stend-start

and run it a few times on your machine -- on mine, an old K5-300
with win98 and Python 2.1:

D:\py21\ew>python oo.py
0.782174525218
0.336476474631

D:\py21\ew>python oo.py
0.750641981931
0.333293384066

D:\py21\ew>python oo.py
0.977303508272
0.426369030658

D:\py21\ew>

You can see the 'run-amuck functional code' is way over
twice faster than the plain loop.


> Python is really pleasant to code in and mostly well designed.  I just
> keep hitting what seem like little lapses of common sense.

In most cases it's probably just your perception being skewed, in
my guess.  There _are_ a small amount of warts (print>> comes
to mind), but not in such fundamental things as loops &c, IMHO.


> Here's another one: the print statement puts a gratuituous space after
> each thing you print.  So
>
>    for i in ['a','b','c']:
>      print i,
>
> prints "a b c " instead of "abc".

Yes, print is meant to be a convenience, based on the idea that
you usually do want to white-separate output.  the write method
of file objects, e.g. sys.stdout.write(i), is handy for when you
don't, although one usually prepares a string and then prints that;
for your case, I'd say
    print ''.join(['a','b','c'])
rather than looping.


Alex






More information about the Python-list mailing list