对于多个功能:ftn_1,ftn_2,...,ftnk 我想在上面随机重复10次。 (整个时间是k ^ 10。)
我发现一些函数的行为类似于这种方式,但它似乎只对字符串起作用:itertools.product
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class IndexController extends Controller
{
public function index(Request $request)
{
$data = $request->all(); //get all input
//$data = $request->input('testing'); //$_POST['testing']
return view('index', ['data' => '$data']);
//return view('index', compact('data'));
//return view('index');
}
我想做类似上面的事情,并找到所有情况下的最小值。
答案 0 :(得分:1)
您只需要创建所有函数的列表(或元组),然后在其上随机使用,例如:
import random
funcs = [ftn1, ftn2, ftn3, ..., ftnN]
my_func = random.choice(funcs)
然后,您可以使用任意选择的参数调用my_func
。
答案 1 :(得分:0)
如果您表示自己拥有k
个函数,并且希望总共10
次调用所有这些函数,但是以随机顺序调用,则可以shuffle()
列出它们。
为了理智起见,此示例具有3个功能,并调用了2次。也为所有这些参数都提供了一个参数,它被写成:
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)
示例输出(当然,由于随机性而有所不同)
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
尽管它们的数量不是3 ^ 2,而是3 * 2。