0
Doing random functions
I have defined many functions in my code and I want to do a random one of them every time in a for loop. How can I do this?
16 ответов
+ 2
Here an example of calling randomly chosen (but completely different) function with randomly chosen list of different length.
https://code.sololearn.com/c7V05Nk38NlM/#py
+ 3
You may try this :
Suppose you have 10 functions.. Number them from 1 to 10... Then, declare a list of no 1 to 10. Choose any one from them randomly and then it will call that function.
P.S. If you don't want to repeat a particular function till all are called, then delete that number from the list once it is called..
You can see an example here.
https://code.sololearn.com/cRXtxzwL9ds5/?ref=app
+ 3
Function names can be put into an iterable like any other value. So you can store them in an iterable and choose randomly from them.
def a():
...
def b():
...
def c():
...
random.choice([a, b, c])()
+ 2
You may find answer in https://www.geeksforgeeks.org/random-numbers-in-JUMP_LINK__&&__python__&&__JUMP_LINK/.
+ 2
You should import a module name random
Import random.
And .random function will help you
+ 1
Ahmad Tarek here is one of my codes which randomizes several games at once.
https://code.sololearn.com/cRWcG3XDpFpL/?ref=app
+ 1
HonFu
Thank you very much you helped me a lot!
But what if one of the fuctions has one parameter or more?
+ 1
@Ahmed Tatek
In reply to your last post (and using HonFu example code):-
import random
def a(*args):
print(*args, "Function", a.__name__, "was chosen.")
def b(*args):
print(*args, "Function", b.__name__, "was chosen.")
def c(*args):
print(*args, "Function", c.__name__, "was chosen.")
random.choice([a, b, c])(12, 13, 14)
+ 1
How do you want to randomly choose them anyway?
(Maybe we need more info now about what you actually want to do.)
+ 1
You already told us that. But what is the code about? What will the functions do? Why do they need different parameters?
+ 1
@Ahmad Tarek
inside each of the functions you can do a "for in loop" and do whatever you need with them.
e.g
for x in args:
blah blah blah
+ 1
HonFu
It was just assumig somecondition.
I have just finished my code because of your help.
+ 1
Glad to hear that.
Can be tricky. If you want to loop, you normally need similarish conditions.
+ 1
I guess that's pythonic.
Parameter: Bucket for a bunch of random stuff.
Function body: Sorting out all the junk before anything else.
0
rodwynnejones
But each function may have different parameters