所以我定义了一个函数,它生成一个名为random_matrix
的二进制整数的随机n×m矩阵。出于此目的,我只对生成二进制矢量即尺寸为n×1的矩阵感兴趣。这些由列表表示。我还定义了一个函数,它接受二进制整数的输入向量,并输出一个带有位翻转的向量,其中给定的出现百分比称为bf_2
。
现在我想要的是Alice生成一个随机输入向量,Bob有一个相同的向量,Eve有一个翻转版本的Alice的向量。所以我使用下面的代码:
import functions_module as fm
input_length = int(input('What is the length of the input string?'))
error = int(input('What is the percentage error in the string received by Eve?'))
Alice = fm.random_matrix(input_length,1)
Bob = Alice
Eve = fm.bf_2(Alice,error)
print(Alice)
print(Bob)
print(Eve)
然而,这为Alice,Bob和Eve提供了相同的输出,这不是我想要的。它与我定义变量Alice,Bob和Eve的方式有关。任何帮助将非常感激!我想要输出的东西
[0,0,0,0]
[0,0,0,0]
[0,0,1,0]
我在下面给出了我的位代码。
def bf_2(bit_string,percentage_error):
"""Bit flips the input string for a given percentage of occurence"""
from random import randint
bits = bit_string
for i in range(0,len(bits)):
r = randint(1,100)
if r <= percentage_error:
if bits[i] == 0:
bits[i] = 1
else:
bits[i] = 0
return bits
答案 0 :(得分:1)
Bob = Alice
这并不是你所期望的。现在您有两个名称引用相同的对象。使用任一变量的修改对两个变量都是可见的(因为它们是同样的东西。)
您需要复制对象。使用copy.deepcopy
通常是最安全的方法。它不仅复制给定对象,还复制它引用的所有对象,确保您不会在复制的顶级对象之间共享内部引用。
import copy
Bob = copy.deepcopy(Alice)