【问题标题】:what is the difference between, the following two while loops logics.?以下两个while循环逻辑有什么区别。?
【发布时间】: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


    【解决方案1】:

    区别如下:

    • 在第一种方法中,您始终替换当前基因,即使它的适应度较差(您始终设置child=mutate(child))。
    • 在第二种方法中,您不断地突变相同的基础基因(不替换它),直到您提高适应度,然后然后将其替换为刚刚获得的改良基因(只有在适应度提高时才设置bestParent=child)。

    希望这会有所帮助。

    【讨论】:

    • 有道理。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多