<分区>
我正在尝试了解遗传算法的工作原理。就像我通过尝试在我的上写东西来学习的一切一样;然而,我的知识非常有限,我不确定我是否做对了。
此算法的目的是查看如果一半的牛群已经感染了疾病,则需要多长时间才能将一半的牛群感染。这只是我想到的一个例子,所以我不确定这是否是一个可行的例子。
关于如何提高我的知识的一些反馈会很好。
代码如下:
import random
def disease():
herd = []
generations = 0
pos = 0
for x in range(100):
herd.append(random.choice('01'))
print herd
same = all(x == herd[0] for x in herd)
while same == False:
same = all(x == herd[0] for x in herd)
for animal in herd:
try:
if pos != 0:
after = herd[pos+1]
before = herd[pos-1]
if after == before and after == '1' and before == '1' and animal == '0':
print "infection at", pos
herd[pos] = '1'
#print herd
pos += 1
except IndexError:
pass
pos = 0
generations += 1
random.shuffle(herd)
#print herd
print "Took",generations,"generations to infect all members of herd."
if __name__ == "__main__":
disease()