running a random function

Roberto Bonvallet rbonvall at gmail.com
Thu Jun 7 13:28:29 EDT 2007


On 7 jun, 11:56, David Bear <david.b... at asu.edu> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.

Try this:

def f(x):
    print "Calling f with arg %s" % x
def g(x):
    print "Calling g with arg %s" % x
def h(x):
    print "Calling h with arg %s" % x

import random
functions = [f, g, h]
for i in range(10):
    random.choice(functions)(25)

HTH, cheers.
--
Roberto Bonvallet




More information about the Python-list mailing list