以下两个 while 循环逻辑之间有什么区别?

what is the difference between, the following two while loops logics.?

我正在尝试实现以下代码。 我在这里尝试了 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

区别如下:

  • 在第一种方法中,你总是替换当前基因,即使它的适应性更差(你总是设置child=mutate(child))。
  • 在第二种方法中,你一遍又一遍地改变相同的基础基因(不替换它)直到你提高适应度,只有这样你用刚刚获得的改良基因替换它(你只设置bestParent=child当适应度提高时)。

希望对您有所帮助。