我从一本书中复制了一个遗传密码,然后发现了这个作业:
childGenes[index] = alternate \
if newGene == childGenes[index] \
else newGene
完整的代码是这样的:
main.py:
from population import *
while True:
child = mutate(bestParent)
childFitness = get_fitness(child)
if bestFitness >= childFitness:
continue
print(str(child) + "\t" + str(get_fitness(child)))
if childFitness >= len(bestParent):
break
bestFitness = childFitness
bestParent = child
人口:
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):
total = 0
for i in range(len(target)):
if target[i] == guess[i]:
total = total + 1
return total
"""
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)
赋值在mutate函数中的密布于person.py中。我从未见过这种变量分配。这是什么? “ \”符号是什么意思?
最佳答案
它可以替代:
if newGene == childGenes[index]:
childGenes[index] = alternate
else:
childGenes[index] = newGene
关于python - 这是什么作业? python ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45837555/