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

时间:2018-09-19 01:11:45

标签: python python-3.x while-loop logic genetic-algorithm

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

1 个答案:

答案 0 :(得分:0)

区别如下:

  • 在第一种方法中,即使当前基因的适应性较差,也要始终进行替换(始终设置child=mutate(child))。
  • 在第二种方法中,您不断重复相同碱基的基因(无需替换),直到提高适应性为止,然后 将其替换为刚刚获得了改良的基因(只有在适应度提高时才设置bestParent=child)。

希望这会有所帮助。