Friday, December 21, 2018

Python - Choose a Function at Random

If you need to randomly select from a number of defined functions, this is a simple way to achieve that:

import random

def function_A(some_var):
    return("{} - A".format(some_var))

def function_B(some_var):
    return("{} - B".format(some_var))

def function_C(some_var):
    return("{} - C".format(some_var))

#Run a random function with the input of "blahblah"
random.choice([function_A, function_B, function_C])("blahblah")
#do it as many times as you'd like, and you'll get different results
random.choice([function_A, function_B, function_C])("blahblah")
random.choice([function_A, function_B, function_C])("blahblah")
random.choice([function_A, function_B, function_C])("blahblah")
random.choice([function_A, function_B, function_C])("blahblah")

No comments:

Post a Comment