大N的[1,2,3,…,N]的抽样置换

2024-05-16 06:36:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须用一个我必须为家庭作业写的genetic algorithm来解the Travelling Salesman Problem。在

问题包括52个城市。因此,搜索空间是52!。我需要随机抽样(比如)1000个排列的range(1, 53)作为我的遗传算法的初始种群的个体。在

为了做到这一点,我试着:

>>> random.sample(itertools.permutations(range(1, 53)), 1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/random.py", line 314, in sample
    n = len(population)
TypeError: object of type 'itertools.permutations' has no len()

所以我试过了

^{pr2}$

但是,鉴于52!非常大,list操作将耗尽我计算机上的内存和交换空间。我不能只选取itertools.permutations生成的前1000个排列,因为它非常具有确定性,这会使我的遗传算法产生偏差。在

有没有更好的方法来实现这种抽样?在


Tags: thesampleinlenline空间rangerandom
1条回答
网友
1楼 · 发布于 2024-05-16 06:36:49

你根本不需要更换。呼叫random.sample(range(52), 52)1000次。在

备注:在所有工作中,您确实应该使用基于零的索引(range(52),而不是{})。这样事情通常会好一些。在

相关问题 更多 >