John Smith John Smith - 1 year ago 53
Python Question

Is this a genetic algorithm?

I am trying to make a genetic algorithm that finds the word given in the console input. But I don't know if I succeeded to do a full genetic algorithm.
Here is the code:

from population import Population

target = input()
maxPop = 10
mutation = 100


pop = Population(target, maxPop, mutation)

import random
from ADN import genetic

class Population:
def __init__(self, target, maxPop, mut):
adn = genetic()
self.popul = []
i = 0
while i < maxPop:

#oldPop = self.popul, target)
while target not in self.popul:
oldPop = self.popul
self.popul =, target)
if target in self.popul:

import random

class genetic:
def genFirst(self, length):
bestGenes = ""
self.letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890[],. "
word = ""
i = 0
while i < length:
word += random.choice(self.letters)
return word

def fitness(self, oldPop, target):
newPop = []

j = 0
for word in oldPop:
newW = ""
for letter in word:
if(letter not in target):
letter = random.choice(self.letters)
if(target.index(letter) != word.index(letter)):
letter = random.choice(self.letters)
newW += letter

return newPop

If it is not a full genetic algorithm, what is missing?

Answer Source

No, it's not a genetic algorithm. It is not even an evolutionary algorithm. It misses the fitness function which should calculate how good is every member of the calculation. After that you should decide which code would you want to make: genetic or evolutionary. Being a beginner you should try the evolutionary algorithm, it's easier and it does not contain the crossover function (which is difficult for beginners). Try this:

import random

genes = "abcdefghijklmnopqrsttuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-[]()1234567890;<>?/ "
target = input()

def genPar(length):
    parent = []
    for i in range(length):

    return "".join(parent)

def fitness(parent):
    total = 0
    for i in range(len(parent)):
        if(parent[i] == target[i]):
            total += 1
    return total

def mutate(parent):
    index  = random.choice(range(len(parent)))
    child = []

    for i in range(len(parent)):
        if(i == index):
            letter = random.choice(genes)
            letter = parent[i]

    return "".join(child)

parent = genPar(len(target))
bestPar = parent
bestFitness = fitness(parent)


generations = 1

while True:
    child = mutate(bestPar)
    childFit = fitness(child)

    if(childFit > bestFitness):
        bestFitness = childFit
        bestPar = child

    generations += 1

    if(child == target):

print("\nGenerations: " + str(generations))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download