Call Functions at Random then Call a Different Function in Python

Viewed 80

I am using random.choice() to randomly call functions in a list. It works ok but sometimes one of the criteria in the called function is not met so it does not run. When this happens I would like to call another, different function from the list.

func_list is populated dynamically and there may be one or multiple functions in the list.

Here's the code:

func_list[func_one, func_two, func_three]
random.choice(func_list)()

So, for example, say func_two was called but criteria in the function was not met I would like to call either func_one or func_three chosen at random. If the criteria in that function is not met I would like to call the other one.

Is it possible to do this?

4 Answers

To avoid calling the same function twice, I suggest shuffling the list and trying the functions one by one, e.g.

func_list = [func_one, func_two, func_three]
func_list_shuffled = func_list[:]  # shallow copy
random.shuffle(func_list_shuffled)

for func in func_list_shuffled:
    try:
        func()
    except:
        pass
    else:
        # no exception ocurred
        break
else:
    print("all functions errored")

A naive approach would be to add func_list as an argument to all of your functions and call the random.choice() if default function criteria is not met inside your functions. This would create a recursive solution until one of the functions do get executed.

Drawback: Might continue infinitely if none of the functions meet the criteria.

Just keep trying until it eventually works and remove the item from the list so it can't be called again:

func_list[func_one, func_two, func_three]

while true:
    i = random.choice(range(func_list))
    try:        
        return func_list[i]()
    except:
        func_list = func_list.remove(i)

Just try out random chosen functions till something works, but remove them from the list if they do not provide the desired result


# let functions follow this pattern
def base_func():
   if criterium:
       return False
   else:
       # Do something
       return True

func_list[func_one, func_two, func_three]

result = False
while result is False:
   if func_list == []:
       break
   chosen_func = random.choice(func_list)
   func_list.remove(chosen_func)  # Remove used function
   result = chosen_func()
Related