我需要用遗传算法解决旅行商问题,这是我的作业。该问题包含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()
所以我尝试了
>>> random.sample(list(itertools.permutations(range(1, 53))), 1000)
然而,考虑到
52!
非常大,list
操作会占用计算机的内存和交换空间。我不能只选择由itertools.permutations
生成的前1000个排列,因为这是非常确定性的,会对我的遗传算法产生偏差。有更好的方法来实现这种抽样吗?
p = range(10); random.shuffle(p)
吧?random.sample
会重复一些值并省略其他值。但也许你是在说这些实际上不必是排列... - senderle