Dumb python questions

Quinn Dunkan quinn at hork.ugcs.caltech.edu
Wed Aug 15 18:12:26 EDT 2001


On 15 Aug 2001 02:58:26 -0700, Paul Rubin <phr-n2001 at nightsong.com> wrote:
>xrange apparently doesn't malloc the values until they're used, but
>they eventually get malloc'd.  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

In python, as in most languages (especially most functional languages),
space and time efficiency is not the goal.  It's possibly a goal, but not
*the* goal.  Programmer efficiency is the goal.

I have a feeling that you're not really running out of memory because of your
100 element lists.  Instead, I think some assembly-loving part of you,
fiercely devoted to that tin god eifficiency, is exclaiming "but it's not as
efficient as it could be!  forget the big picture, optimization is the key!".

Ignore that annoying little voice.  Wait until you actually have a problem, in
memory or speed.  Then find out which part of your program has the problem.
Then use a less naive algorithm:

def sum(low, high):
    p = high - low + 1
    if p % 2:
        return (low + high) * (p // 2) + (low + high)//2
    else:
        return (low + high) * (p // 2)

>Python is really pleasant to code in and mostly well designed.  I just
>keep hitting what seem like little lapses of common sense.
>
>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".

The spaces are as gratuitous as all the spaces you put in between your words.
It has a lot of common sense: spaces seperate things nicely.  'print' is
supposed to be quick and easy to use for printing out short messages.  That's
why it's a statement (no parens), automatically converts its arguments to
strings, puts spaces in between its elements, and puts a newline on the end (I
personally wouldn't mind if we dropped the "print foo," syntax, which is
irregular and tends to lead to confusing extraneous softspace spaces).  If
'print' didn't put in all those gratuitous spaces and newlines, I'd wind up
having to put them in by hand myself most of the time (as I do in some other
languages).

If you want "low level" control over your IO, use the low level interface:
sys.stdout.write.  'print' is optimized for casual use.  You can also use the
string formatting operator, %.


And if you're so big on common sense, why didn't you just write

print 'abc'


<wink>



More information about the Python-list mailing list