如何在Python枚举中更改所需的索引号?

2024-06-17 12:42:09 发布

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

我正在尝试用Python编写汉明码编码,我被困在必须计算奇偶校验位索引的部分。你知道吗

汉明码是使用额外的奇偶校验位来识别单个错误。按如下方式创建代码:

将2的幂的所有位位置标记为奇偶校验位。(位置1、2、4、8、16、32、64等) 所有其他的位位置都是用来编码数据的。(位置3、5、6、7、9、10、11、12、13、14、15、17等) 每个奇偶校验位计算码字中某些位的奇偶校验。奇偶校验位的位置决定了它交替检查和跳过的位序列。你知道吗

位置1:检查1位、跳过1位、检查1位、跳过1位等(1,3,5,7,9,11,13,15,…)

位置2:检查2位、跳过2位、检查2位、跳过2位等(2、3、6、7、10、11、14、15……)

位置4:检查4位、跳过4位、检查4位、跳过4位等(4、5、6、7、12、13、14、15、20、21、22、23……)

位置8:检查8位、跳过8位、检查8位、跳过8位等(8-15、24-31、40-47……)

位置16:检查16位、跳过16位、检查16位、跳过16位等(16-31、48-63、80-95,…)

位置32:检查32位、跳过32位、检查32位、跳过32位等(32-63、96-127160-191,…) 等等

如果奇偶校验位所检查位置的奇偶校验位总数为奇数,则将奇偶校验位设置为1。如果检查位置中的奇偶校验位总数为偶数,则将奇偶校验位设置为0。你知道吗

基本上,我需要在索引处生成奇偶校验位:

P1=[1,3,5,7,9,11等]

P2=[2,3,6,7,10,11等]

P3=[4、5、6、7、12、13等]

P4=[8,9,10,11,12,13,14,15,24等]

一旦找到这些,我需要加上位,模2和插入在正确的位置。你知道吗

我的代码找到插入的位置

# Function to calculate Hamming code
def hamming(number):
    print("Hamming Code - Beginning to encode. ")
    listP = half_ham(number)
    print("Inserting P at relevant indices: ", listP)
    encode = []
    print("Length of messgae: ",len(listP), "bits.")
    index = []
    for i, j in enumerate(listP, start = 1):
        print("i", i)
        if isPowerOfTwo(i):
            index = gen_indices(i, len(listP))
            c = [ listP[i] for i in index]  
            print("C: ", c)

# Function to insert P at positions which are powers of 2
def half_ham(bin_str):
    parity_positions = [2**i for i in range(0, len(bin_str))]
    ret = []
    current_index = 1
    indexDict = {}
    while (len(bin_str) > 0):
        if current_index in parity_positions:
            ret.append('P')
        else:
            ret.append(bin_str[0])
            bin_str = bin_str[1:]
        current_index += 1 
    return ret

输入:

hamming("10101010")

电流输出:

Hamming Code - Beginning to encode. 
Inserting P at relevant indices:  ['P', 'P', '1', 'P', '0', '1', '0', 'P', '1', '0', '1', '0']
Length of message:  12

现在我需要找到正确的奇偶校验索引(P1,P2,P3如上)。你知道吗

最初,我试图用while循环生成索引。直到我得到一个超出范围的错误列表。加上它几乎不可读。你知道吗

# Function to get a list of the indexes
def gen_indices(x, y):
    jump = x
    current = x
    index = []
    while current <= y:
        index.extend(list(range(current, current+jump)))
        print("before current:",current)
        current += jump * 2
    return index

现在我尝试使用枚举函数来获得所需索引的列表。比如:

def index(x, listP):

    for x, y in enumerate(listP, start = x):

        print(x,y)

期望输出为:

P1=1 p P2=2 p 3 1 3 1 5 0 6 1 7 1 7 1

从这里我可以把这些位加起来形成一个字符串。有人能帮忙吗?你知道吗

我希望这是有道理的。我是一个非常新的编码,所以请不要判断。你知道吗


Tags: oftoinforindexlenbindef