Wednesday, July 8, 2009

Methinks it is like a Python

On Monday, my second book on Python programming arrived in the mail. My first, Learning Python (O'Reilly), is well written but slow- I learn best by plowing through some examples and then filling in the gory details. Learning Python works in the opposite direction, so I grabbed Python Scripting for Computational Science (Springer). This book has been great for getting up to speed post-haste.

Now that I've had some free time, I've spent the past two evenings playing with the Python language and was able to recreate Richard Dawkin's "Weasel" program. This program takes a target phrase, "Methinks it is like a weasel" (Shakespeare, anyone?), and a random group of letters of the same length. Over each iteration, an offspring of the jumbled phrase is created by randomly changing some of the letters. Of X offspring, the one nearest the target phrase (the "fittest") is chosen and another generation is made. Eventually, and rather quickly, you achieve the target phrase through a set of random mutations guided by a judgment of fitness -- a neat demonstration of the principles of evolution.

Although I was able to create this program quickly using Perl, I thought it would be an excellent Python exercise. I was able to hack together a version pretty quickly, but given the powerful matplotlib package, was able to go a step further and visualize some of the results.

Convergence to the target phrase in 8332 iterations. Each generation produced 10 children phrases; each letter for each child phrase had a 0.1% chance of mutation.

Not too shabby for a few hours work. Compared to my Perl version, the source code is shorter but feels much less elegant. They both run very quickly. Python gets points for the ease of visualization through matplotlib; Perl gets points for easily integrating into a CGI script for web browser interface (though Python supposedly does this equally as well.) The comparisons won't be fair until I've given Python more than a few days' worth of work.

Here's a good online version of Weasel.
Here's another.

No comments:

Post a Comment