【发布时间】:2018-09-19 01:11:44
【问题描述】:
我正在尝试实现以下代码。 我在这里尝试了 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
【问题讨论】:
标签: python python-3.x while-loop logic genetic-algorithm