1st non-trivial program - gentle criticism requested

Alex cut_me_out at hotmail.com
Thu Apr 13 10:30:10 EDT 2000


> With some trepidation, I post it here in the hopes that experts will
> be able to coach me in "The Python Way".

I'm by no means an expert.  Python is the first language I've used
extensively since I was a kid.  But I've been using it for close to a
year, and have acquired a couple of prejudices.

If I was going to write a program like this, practically everything
would have been inside a class.  This would have avoided the need for
global variables (looking at this script, I realized that I have never,
ever used a global variable in a python script.  I've never written a
really complex application, though.)  

Also, for extended calculations like yours, having everything in a class
makes it possible to stop the calculation, tinker with the innards of
the class, and restart it.  E.g.

class Weasle:
    '''etc. etc.'''
    pass

if ('weasle' not in dir ()):
    weasle = Weasle ()
else:
    weasle.__class__ = Weasle

weasle.run ()

...then you pump this into an interactive interpreter (I use emacs
python-mode for this), stop it whenever it seems to be going awry, edit
the script, and pump it back into the interpreter.  The weasle instance
gets all the new methods from your editing but keeps its old data, so
you don't have to start it up over and over and wait till it reaches the
point you want to study.  

If you want to speed up MutateIndividual, you might try something like
this untested code:

import random

def MutateIndividual (theTargetIndiv):
   """Iterates over symbols of individual changing their 'genes'"""
   # Must be a faster way of doing this
   theNewIndiv = []
   for theSymbol in theTargetIndiv:
      if (gRng.random() < gMutationRate):
         theNewIndiv.append (random.choice (gAlphabet))
      else:
         theNewIndiv.append (theSymbol)
   return string.join (theNewIndiv)

also, your findMax method seems redundant.  I think you could do
something like:

best_score = max (theFitness)
# Index of first element == best_score:
best_index = theFitness.index (best_score) 
theWinner = gPopulation[best_index]

Alex.



More information about the Python-list mailing list