Python - How to replace character in list by index - Genetic algorithm

61 Views Asked by At

How am I able to swap character by the index. This is how I've done that already, but I guess there might be many mistakes.

All I'm struggling right now is changing 0 to 1, and 1 to 0 in case of mutation class.

I've tried many methods but I must say I gave up cause I've been doing weird mistakes, especially I'm still learning that from 0.

import random

a = 4
b = 7
c = 2

def function(x):
    return x[0]**2.0 + x[1]**2.0

# boots - how many times program should go on
boots = 40

number_pop = 4

pop_people = 4

pr_cross = 50

pr_mut = 40

#gener. 1st population
def population():
    z = []
    for i in range(pop_people):        
        r = f'{random.randint(0, 255):08b}'
        z.append(r)
    print("New population: ", z)
    return z
# population()

def crossing():
    tab_cross = []
    tab_cross = population()
    a_cross = []

    for o in range(0, pop_people, 2):
        w_lb_psl = random.randint(0, 100)
        if w_lb_psl > pr_cross:
            pc = 3

            p1_1 = tab_cross[o][0:pc]
            p1_2 = tab_cross[o][pc:8]

            p2_1 = tab_cross[o+1][0:pc]
            p2_2 = tab_cross[o+1][pc:8]

            a_cross.append(p1_1 + p2_2)
            a_cross.append(p2_1 + p1_2)

        else:
            a_cross.append(tab_cross[o]) 
            a_cross.append(tab_cross[o+1])
    print("Population after cross: ", a_cross)
    return a_cross
# crossing()

def mutation():
    tab_mut = []
    tab_mut = crossing()

    for m in range(pop_people):
        w_lb_psl = random.uniform(0, 100)
        if w_lb_psl < pr_mut:
            for x in tab_mut:
                if x == 1:
                    tab_mut[x] = 0
                elif x == 0:
                    tab_mut[x] = 1

    print("Population after mutation: ", tab_mut)
    return tab_mut

mutation()

0

There are 0 best solutions below