Reputation: 275
I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.
Input:
def a():
print('a')
def b():
print('b')
def c():
print('c')
shuffle([a,b,c])
This is output what I want:
a
b
c
or
a
c
b
or
c
b
a
or etc How to run functions with random order?
Upvotes: 2
Views: 2848
Reputation: 239623
random.shuffle
is an in-place operation. So you need to keep the list separately and shuffle it.
import random
functions = [a, b, c]
random.shuffle(functions)
Now, the functions are shuffled and you just have to execute them
for func in functions:
func()
You can probably store this in a function and do it like this
def run_functions_in_random_order(*funcs):
functions = list(funcs)
random.shuffle(functions)
for func in functions:
func()
run_functions_in_random_order(a, b, c)
Or you can simply use the functions in closures, like this
def run_functions_in_random_order(*funcs):
def run():
functions = list(funcs)
random.shuffle(functions)
for func in functions:
func()
return run
random_exec = run_functions_in_random_order(a, b, c)
random_exec()
random_exec()
random_exec()
Upvotes: 8
Reputation: 4132
Here is how I would do. Basically what thefourtheye has suggested. Run this Code
from random import shuffle
def a():
print('a')
def b():
print('b')
def c():
print('c')
def main():
lis = [a,b,c]
shuffle(lis)
for i in lis:
i()
Upvotes: 1
Reputation: 31
Or make a list and take random:
import random
def a():
print('a')
def b():
print('b')
def c():
print('c')
my_list = [a, b, c]
random.choice(my_list)()
Upvotes: 1