Search code examples
pythonalgorithmgenetic-algorithmmutation

Randomly flip one bit in a binary list


I am using python-3.x, and I am trying to do mutation on a binary string that will flip one bit of the elements from 0 to 1 or 1 to 0 by random, I tried some methods but didn't work I don't know where is the problem:

x=[0, 0, 0, 0, 0]

def mutation (x, muta):
    for i in range(len(x)):
        if random.random() < muta:
            x[i] = type(x[i])(not x[i])
    return x,
print (x)

The output for example should be x=[0, 0, 0, 1, 0] or x=[1, 0, 0, 0, 0] and so on....

Also, I tried this one:

MUTATION_RATE = 0.5
CHROMO_LEN = 6
def mutate(x):
    x = ""
    for i in range(CHROMO_LEN):
        if (random.random() < MUTATION_RATE):
            if (x[i] == 1):
                x += 0
            else:
                x += 1
        else:
            x += x[i]
    return x
print(x)

please any suggestion or advice will be appreciated


Solution

  • Are you sure you're calling the function before printing x:

    def mutation(x):
        # your code without the trailing comma
    
    mutation(x)
    print(x)
    

    In Python, creating a new list is usually preferable to mutating an old one. I would write your first function like this (I converted the integers to booleans because you're just flipping them:

    x = [False, False, False, False]
    
    
    def mutation(x, muta):
        return [not e if random.random() < muta else e
                for e in x]
    

    Change x by assigning to it again:

    x = mutation(x, .5)
    

    Your original function is working if you remove the comma after the return:

    def mutation(x, muta):
        for i in range(len(x)):
            if random.random() < muta:
                x[i] = type(x[i])(not x[i])
        return x
    x = [False, False, False, False]
    
    
    mutation(x, .5)
    Out[8]: [False, False, True, False]
    
    mutation(x, .5)
    Out[9]: [True, True, True, False]