[英]How can repeat 10 times randomly in several available functions in python?
For several functions: ftn_1, ftn_2, ... , ftnk I want to repeat 10 times randomly among above. 对于几个功能:ftn_1,ftn_2,...,ftnk我想在上面随机重复10次。 (The whole time is k^10.)
(整个时间是k ^ 10。)
I find some function which acts like this way but it seems to act just for string : itertools.product 我发现一些函数的行为类似于这种方式,但它似乎仅对字符串起作用:itertools.product
def ftn1():
...
def ftn2():
...
x=0;
itertools.product(x=ftn1(x), x=ftn2(x), .., x=ftnk(x), [repeat=10])
I want to do similar to above and find the smallest value for all cases. 我想做类似上面的事情,并在所有情况下找到最小值。
You just need to create a list (or a tuple) of all your functions, and then use random on it, for instance: 您只需要创建所有函数的列表(或元组),然后在其上使用random即可,例如:
import random
funcs = [ftn1, ftn2, ftn3, ..., ftnN]
my_func = random.choice(funcs)
Then you can call my_func
with any argument of your choice. 然后,您可以使用任意选择的参数调用
my_func
。
If you mean you have k
functions and want to call all of them 10
times in total, but in random order, you could shuffle()
a list of them. 如果您的意思是您有
k
函数,并且希望总共调用10
次,但是以随机顺序,您可以shuffle()
列出它们。
For sanity purposes this example has 3 functions and calls them 2 times. 为了理智起见,此示例具有3个功能,并调用了2次。 An argument is supplied too for all of them, it is just written out:
也为所有这些参数提供了一个参数,它被写成:
import random
def f1(x):
print("f1:"+str(x))
def f2(x):
print("f2:"+str(x))
def f3(x):
print("f3:"+str(x))
# here you could have more functions...
repeats=[f1,f2,f3]*2 # ... and they could be listed here, and 2 could be 10
print("Default order:")
for i in range(len(repeats)):
repeats[i](i) # repeats[i] is a function here, which is invoked with i
random.shuffle(repeats)
print("Shuffled order:")
for i in range(len(repeats)):
repeats[i](i)
Example output (of course it varies because of randomness) 输出示例(当然,由于随机性而有所不同)
Default order: f1:0 f2:1 f3:2 f1:3 f2:4 f3:5 Shuffled order: f3:0 f1:1 f1:2 f2:3 f2:4 f3:5
Though the number of them is not 3^2, but 3*2. 尽管它们的数量不是3 ^ 2,而是3 * 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.