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

2024-09-29 23:19:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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)

如果您有任何建议,我们将不胜感激


Tags: 字符串inforlenreturnifratedef
2条回答

是否确定在打印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]

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

x[1] = x[1] ^ 1

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

相关问题 更多 >

    热门问题