我正在尝试实现以下代码。 我在这里尝试了2种方法(2个while循环)。至少对我来说是相同的但是解决方案之一,即方法2趋向解决方案。 方法1不是。 您能帮助我找出两种方法之间的区别吗? 注意:我使用loopIndex只是为了跟踪执行在哪个循环中。 如果时间太长,我试图终止循环。 谢谢。
# this program tries to guess the target string
# using genetic algorithm.
import random
genList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"
target = "Hello"
# generates a random string under provided length
def generateGuess(_length):
gene = []
for i in range(_length) :
gene.append(random.choice(genList))
return "".join(gene)
# gets the total no of letters matched from string provided, to target string
def getFitness(gene):
return sum(1 for geneVar, targetVar in zip(gene, target) if geneVar == targetVar)
# changes 1 letter of the string provided, at a random position.
def mutate (gene):
newGene, alternate = random.sample(genList, 2)
gene = list(gene)
index = random.randint(0, len(gene) - 1)
gene[index] = alternate if gene[index] == newGene else newGene
return "".join(gene)
# to display the string provided with its fitness calculated.
def display(gene):
print("Gene : {0}, Fitness : {1}".format(gene, getFitness(gene)))
# Approach 1 -------------------------------------
child = generateGuess(len(target))
bestFitness = 0
loopIndex = 0
while True :
loopIndex = loopIndex + 1
child = mutate(child)
if loopIndex > 16800 :
break
childFitness = getFitness(child)
display(child)
print(loopIndex)
if childFitness > bestFitness :
bestFitness = childFitness
if childFitness >= len(target):
break
# Approach 2 -------------------------------------
bestParent = generateGuess(len(target))
bestFitness = getFitness(bestParent)
display(bestParent)
loopIndex = 0
while True:
loopIndex = loopIndex + 1
child = mutate(bestParent)
childFitness = getFitness(child)
display(child)
print(loopIndex)
if bestFitness > childFitness:
continue
if childFitness >= len(bestParent):
break
bestFitness = childFitness
bestParent = child
答案 0 :(得分:0)
区别如下:
child=mutate(child)
)。bestParent=child
)。希望这会有所帮助。