我试图了解遗传算法是如何工作的。就像我通过尝试在我的 on 上写一些东西来学习的所有东西一样;但是,我的知识非常有限,我不确定我是否做对了。
该算法的目的是查看如果一半的人口已经被感染,那么半数牛群感染疾病需要多长时间。这只是我脑海中想到的一个例子,所以我不确定这是否是一个可行的例子。
关于如何提高我的知识的一些反馈会很好。
这是代码:
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()