以下是我的使用方式:
def initialBuild(self):
alphabet = self.alphabet
for i in range (self.length):
value = random.sample(alphabet, 1)
alphabet.remove(value[0])
self.finalWord.append(value[0])
print "Final word = ", self.finalWord
这只是从一个Individual类的init方法中调用的。init方法被如下调用...
def buildPopulation(self, alphabet):
#Initialize empty individuals
for i in range(POPULATION_SIZE):
self.population.append(Individual(alphabet))
init方法如下所示...
def __init__(self, alphabet = []):
self.length = len(alphabet)
self.alphabet = alphabet
self.initialBuild()
最后,我打印了一个最终的单词。这是两次运行此方法的输出结果:
请注意,这两个是完全相同的。最终单词 = [[1150, 1160],[720, 635],[95, 260],[595, 360],[770, 610],[830, 610],[25, 185],[520, 585],[605, 625],[410, 250],[555, 815],[880, 660],[300, 465],[1220, 580],[1215, 245],[1250, 400],[565, 575],[1605, 620],[845, 680],[1170, 65],[795, 645],[525, 1000],[760, 650],[580, 1175],[420, 555],[25, 230],[345, 750],[700, 500],[725, 370],[1530, 5],[1740, 245],[875, 920],[415, 635],[1340, 725],[975, 580],[575, 665],[1465, 200],[830, 485],[660, 180],[475, 960],[685, 595],[145, 665],[510, 875],[845, 655],[650, 1130],[945, 685],[480, 415],[700, 580],[560, 365],[685, 610],[835, 625],[1320, 315]]
最终单词 = [[1150, 1160],[720, 635],[95, 260],[595, 360],[770, 610],[830, 610],[25, 185],[520, 585],[605, 625],[410, 250],[555, 815],[880, 660],[300, 465],[1220, 580],[1215, 245],[1250, 400],[565, 575],[1605, 620],[845, 680],[1170, 65],[795, 645],[525, 1000],[760, 650],[580, 1175],[420, 555],[25, 230],[345, 750],[700, 500],[725, 370],[1530, 5],[1740, 245],[875, 920],[415, 635],[1340, 725],[975, 580],[575, 665],[1465, 200],[830, 485],[660, 180],[475, 960],[685, 595],[145, 665],[510, 875],[845, 655],[650, 1130],[945, 685],[480, 415],[700, 580],[560, 365],[685, 610],[835, 625],[1320, 315]]
编辑:由于我很难挑选出有用而且足够简短的代码放到这篇文章中,所以我已经在pastebin上发布了一大堆代码。 http://pastebin.com/f5f068391 这个希望是更好的选择... 再次感谢
random.sample(..., 1)[0]
is equivalent torandom.choice(...)
- AChampion