在二进制列表中随机翻转一位

问题描述 投票:0回答:2

我正在使用python-3.x,并且我尝试对二进制字符串进行突变,该突变将随机地将元素的一部分从0翻转到1或从1翻转到0,我尝试了一些方法但没有用我不知道问题出在哪里:

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)

例如,输出应为x = [0,0,0,1,0]或x = [1,0,0,0,0],依此类推...。

而且,我尝试了这个:

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)

请提供任何建议或意见

python algorithm genetic-algorithm mutation
2个回答
0
投票

确定在打印x之前确定要调用该函数:

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

mutation(x)
print(x)

在Python中,创建新列表通常比对旧列表进行突变更可取。我会这样写您的第一个函数(我将整数转换为布尔值,因为您只是将它们翻转:

x = [False, False, False, False]


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

通过再次分配来更改x

x = mutation(x, .5)

如果您在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]

0
投票

您还可以使用python的XOR operator翻转位,这将在'1'和'0'之间翻转:

x[1] = x[1] ^ 1

另请参见:Python XOR preference: bitwise operator vs. boolean operators

© www.soinside.com 2019 - 2024. All rights reserved.