Lab 7 - Genetic Algo
Lab 7 - Genetic Algo
ipynb - Colab
Search Algorithm
4. Crossover: For each pair to be mated, a crossover point is chosen randomly from the
positions in the string.
the offspring themselves are created by crossing over the parent strings at the
crossover point.
For example, the first child of the first pair gets the first three digits from the first
parent and the remaining digits from the second parent,
whereas the second child gets the first three digits from the second parent and the
rest from the first parent.
5. Mutation: each location is subject to random mutation with a small independent
probability.
https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 1/5
4/24/24, 12:08 PM Lab 7 - Genetic Algo.ipynb - Colab
1. input function: takes size of sack, number of items in sack from user and then ask user to
choose whether
https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 2/5
4/24/24, 12:08 PM Lab 7 - Genetic Algo.ipynb - Colab
2. Choose the right encoding to express these items for random inital population generation,
where N=12
4. Select the genes (most fitted) according to your problem using rank based, roulette wheel,
tournament selction method
Display childs after cross over along with parents to show comparison
Display childs after mutaion along with privious childs to show comparison
7. repeat this process till termination condition or you find a sloution.
import random
# Valid genes
GENES = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP
QRSTUVWXYZ 1234567890, .-;:_!"#%&/()=?@${[]}'''
class Individual(object):
'''
https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 3/5
4/24/24, 12:08 PM Lab 7 - Genetic Algo.ipynb - Colab
@classmethod
def mutated_genes(self):
'''
create random genes for mutation
'''
global GENES
gene = random.choice(GENES)
return gene
@classmethod
def create_gnome(self):
'''
create chromosome or string of genes
'''
global TARGET
gnome_len = len(TARGET)
return [self.mutated_genes() for _ in range(gnome_len)]
def cal_fitness(self):
'''
Calculate fitness score, it is the number of
characters in string which differ from target
string.
'''
# Driver code
def main():
global POPULATION_SIZE
#current generation
generation = 1
found = False
population = []
https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 4/5
4/24/24, 12:08 PM Lab 7 - Genetic Algo.ipynb - Colab
s = int((10*POPULATION_SIZE)/100)
new_generation.extend(population[:s])
population = new_generation
generation += 1
if __name__ == '__main__':
main()
https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 5/5