我必须用一个我必须为家庭作业写的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个排列,因为它非常具有确定性,这会使我的遗传算法产生偏差。在
有没有更好的方法来实现这种抽样?在
你根本不需要更换。呼叫
random.sample(range(52), 52)
1000次。在备注:在所有工作中,您确实应该使用基于零的索引(})。这样事情通常会好一些。在
range(52)
,而不是{相关问题 更多 >
编程相关推荐