calling functions

jepler at unpythonic.net jepler at unpythonic.net
Mon Aug 1 20:07:19 EDT 2005


Without a 'global' statement, all variables which are assigned in the body of a
function are local to that function.

Here is an example showing that f() does not create a module-level variable,
but g() does.

>>> def f():
...     z = 3
... 
>>> def g():
...     global z
...     z = 3
... 
>>> z
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'z' is not defined
>>> f()
>>> z
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'z' is not defined
>>> g()
>>> z
3

You also have a fencepost error in your slicing.  You want to write
	child = parent[:position] + gene + parent[position+1]
otherwise you end up including too few characters in child, and if
position is 0 you get an even more unexpected result.

However, instead of using 'global' you should just have mutate() return
the new child.  Here's a version of mutate() that I wrote:
	import string, random
	valid = string.lowercase + " "

	def mutate(parent):
	    position = random.randrange(len(parent))
	    newgene = random.choice(valid)
	    return parent[:position] + newgene + parent[position+1:]
My mutate() returns the new string after it is mutated, so there's no
need to use 'global'

Here, I repeatedly mutate child to give a new child:
>>> child
'forest of grass'
>>> for i in range(5):
...     child = mutate(child)
...     print child
... 
forest of grays
forqst of grays
fooqst of grays
zooqst of grays
zooqst of brays

Here, I find many mutations of parent:
>>> for i in range(5):
...     child = mutate(parent)
...     print child
... 
foresf of grass
forestsof grass
forest ofpgrass
forest oj grass
forest cf grass

If you have a fitness function f() which returns a higher number the
more fit a string is, and you're using Python 2.4, here is some code to
order several mutations of parent according to fitness:
>>> children = sorted((mutate(parent) for i in range(5)), key=f, reverse=True)
>>> fittest_child = children[0]

Here's a stupid fitness function:
	def f(s): return f.count(" ")

And it's fairly successful at breeding a string with lots of spaces:
>>> child = "forest of grass"
>>> for i in range(10):
...     children = (mutate(child) for j in range(100))
...     child = sorted(children, key=f, reverse=True)[0]
...     print child
... 
f rest of grass
f rest of g ass
f rest yf g ass
f rest y  g ass
f rest y  g a s
t rest y  g a s
t rest y  g a  
t re t y  g a  
t  e t y  g a  
t  e   y  g a  

Over 10 generations, the most fit of 100 mutations is used as the basis for the
next generation.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050801/3e7ab425/attachment.sig>


More information about the Python-list mailing list