1

I am copied from a book a genetic code and I found this assignment:

childGenes[index] = alternate \
    if newGene == childGenes[index] \
    else newGene

The full code is this: 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

population.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):
    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)

The assignment is in population.py, in the mutate function. I have never seen this kind of variable assignment. What is this? What does the "\" symbol mean?

4 Answers4

2

The assignment has been split over multiple lines. The backslash joins the lines. The assignment can be rewritten as:

childGenes[index] = alternate if newGene == childGenes[index] else newGene

This is a conditional expression (sometimes called a "ternary operator") which is equivalent to:

if newGene == childGenes[index]:
    childGenes[index] = alternate
else:
    childGenes[index] = newGene
Alasdair
  • 298,606
  • 55
  • 578
  • 516
1

It translates to:

if newGene == childGenes[index]:
   childGenes[index] = alternate
else:
   childGenes[index] = newGene
damisan
  • 1,037
  • 6
  • 17
0

The backslash here is a simple newline escape character. So the python interpreter reads those lines as one:

childGenes[index] = alternate if newGene == childGenes[index] else newGene

The one line conditional assigment was discussed amongst otheres here:

https://stackoverflow.com/questions/7872838/one-line-if-condition-assignment

Stanislav
  • 155
  • 2
  • 9
0

It is the alternative of:

if newGene == childGenes[index]:
    childGenes[index] = alternate
else:
    childGenes[index] = newGene
Teodor Cristian
  • 349
  • 4
  • 16