我正在使用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)
如果您有任何建议,我们将不胜感激
是否确定在打印
x
之前调用函数:在Python中,创建新列表通常比修改旧列表更可取。我会这样编写您的第一个函数(我将整数转换为布尔值,因为您只是翻转它们:
通过再次分配给
x
来更改它:如果删除
return
后面的逗号,则原始函数可以正常工作:您还可以使用python的XOR operator来翻转位,位将在“1”和“0”之间翻转:
x[1] = x[1] ^ 1
另见:Python XOR preference: bitwise operator vs. boolean operators
相关问题 更多 >
编程相关推荐