我正在研究遗传算法,我发现了一个有效的代码,现在我正在尝试理解,但我看到了这个返回语句:
return sum(1 for expected, actual in zip(target, guess)
if expected == actual)
Run Code Online (Sandbox Code Playgroud)
它有什么作用?
这是完整的代码:
主要.py:
from population import *
while True:
child = mutate(bestParent)
childFitness = get_fitness(child)
if bestFitness >= childFitness:
continue
print(child)
if childFitness >= len(bestParent):
break
bestFitness = childFitness
bestParent = child
Run Code Online (Sandbox Code Playgroud)
人口.py:
import random
geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!.,1234567890-_=+!@#$%^&*():'[]\""
target = input()
def generate_parent(length):
genes = []
while len(genes) < length:
sampleSize = min(length - len(genes), len(geneSet))
genes.extend(random.sample(geneSet, sampleSize))
parent = ""
for i in genes:
parent += i
return parent
def get_fitness(guess):
return sum(1 for expected, actual in zip(target, guess)
if expected == actual)
def mutate(parent):
index = random.randrange(0, len(parent))
childGenes = list(parent)
newGene, alternate = random.sample(geneSet, 2)
childGenes[index] = alternate \
if newGene == childGenes[index] \
else newGene
child = ""
for i in childGenes:
child += i
return child
def display(guess):
timeDiff = datetime.datetime.now() - startTime
fitness = get_fitness(guess)
print(str(guess) + "\t" + str(fitness) + "\t" + str(timeDiff))
random.seed()
bestParent = generate_parent(len(target))
bestFitness = get_fitness(bestParent)
print(bestParent)
Run Code Online (Sandbox Code Playgroud)
这是一个工作遗传算法的完整代码。我修改了一些部分,使其对我来说更具可读性。
return 语句位于population.py 文件中的get_fitness 函数中。
让我们分解一下:
return sum(1 for expected, actual in zip(target, guess)
if expected == actual)
Run Code Online (Sandbox Code Playgroud)
可以写成:
total = 0
for i in range(len(target)):
if target[i] == guess[i]:
total = total + 1
return total
Run Code Online (Sandbox Code Playgroud)
zip(a, b)从a和 制作成对项目的列表b,例如:
zip([1, 2, 3], ['a', 'b', 'c'])
Run Code Online (Sandbox Code Playgroud)
产量[(1, 'a'), (2, 'b'), (3, 'c')]。因此,zip(target, guess)表达式返回一个列表,其中包含第一个项目 fromtarget和第一个项目 of guess,然后是第二个项目 fromtarget和第二个 from guess,依此类推。
该for expected, actual in zip()位从 的输出解包值对zip(),因此对中的第一个 (from target) 转到变量expected,而对中的第二个 (from guess) 转到变量actual。
该1 ... if expected == actual位表示“zip()如果 中的值expected等于 中的值,则为每个项目发出 1的值actual。
sum()将1for 循环中的值的数量相加。
达达!现在您有了预期值和实际值相同的项目数。以这种方式编写它有几个原因:
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |