Improving style (and speed)?

Alex Martelli alex at magenta.com
Fri Aug 4 04:15:03 EDT 2000


"ingo" <ingoogni at CUT.THIS.OUT.home.nl> wrote in message
news:8F866F817seed7 at 212.120.66.218...
> Alex Martelli wrote:
>
> >.....
> >
> >But that's dependent on there being a bug in your
> >code as presented.  Is there...?
> >
> Yes :(

Good!  So, now you know how to simplify your code.


> Thanks Alex, for showing how to approach someting like this, setting up
> a simple table.

You're welcome!  Grab Bentley's "Programming Pearls", published by
Addison-Wesley (and any other book by Bentley), and read through it
slowly and carefully, trying all the exercises; it's a small book, 150 pages
plus appendices, nothing compared to the typical 1000-plus pages books
of today, but does hold an order of magnitude more precious information
and hints per page than the latter, more than evening things up.

> But the step from the table to
> >Posy=Posy+(MinIndex%3)-1
> >Posz=Posz+(MinIndex/3)-1
> would never occured to me.

As you gain more problem-solving experience, you will start noticing how
often there are patterns of regularity in data, and how often you can
exploit
it to simplify your programs.  When you see some value varying with another
on a pattern like a-a-a-b-b-b-c-c-c, a divide-by-three possibility will
occur;
when the pattern is like a-b-c-a-b-c-a-b-c, a modulo-three.  Which is just
one special case (albeit the simplest and most often occurring one) of a
"number in a certain base [or more than one base]" thinking-pattern.

But there's nothing wrong, very often, in keeping the tables.  I would not
be surprised if a table-lookup turned out to be faster anyway:
    Posy=Posy+Deltay[MinIndex]
    Posx=Posx+Deltax[MinIndex]
with, just once out of the loop, bindings
    Deltay=(-1,0,1)*3
    Deltax=(-1)*3+(0)*3+(1)*3

Table-lookups yank your computations out of the loop, so they're done
just once and you don't care much about their cost -- as long as the tables
are reasonably small, such lookups offer speedup AND simplification
together, a neat package:-).  Python offers excellent language support
for such table lookups: lists for simple transformations of small integers
to whatever, dictionaries for more general transformations, and even
string transformation tables for the specific frequent problem of having
to translate/remove certain characters to others (in the string module).
But in most any language, it's a truly fundamental pattern anyway...


Alex






More information about the Python-list mailing list