编码理论算法

2024-10-02 22:36:49 发布

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

这是问题所在,也是我试图解决它的原因,但在调试之后,我意识到我的while循环没有按需要运行。任何帮助都将不胜感激

问题:给定字母q,从字母表中创建大小为n的组合(带替换)列表。如果组合列表中至少有M个元素,其中每个元素与其余元素的差异为d个列表项,则返回True

import itertools as it
import numpy as np

def nmdcode(q, n, M, d):
    combinations = list(it.product(q, repeat=n))
    final_list = []
    
    i = 0
    n = 0
    
    final_list.append(combinations[0])
    checker = []
    result = False
    
    while i < (len(combinations) - 1):
        checker = combinations[i + 1]
        for element in final_list:
            diff = sum(map(lambda x,y: bool(x-y),checker, element))
            if (diff == d):
                final_list.append(checker)
                print(final_list)
        
        i += 1
    
    if (len(checker) >= M):
        result = True
        
    return result
    
print(nmdcode([1,2,5], 10, 200, 3))



Tags: importtrue元素列表lenascheckerit
1条回答
网友
1楼 · 发布于 2024-10-02 22:36:49

这是修改后的工作代码

import itertools as it
import numpy as np

def nmdcode(q, n, M, d):
    combinations = list(it.product(q, repeat=n))
    final_list = []
    
    i = 0
    n = 0
    
    # final_list.append(combinations[0])
    checker = []
    result = False
    
    
    #while i < (len(combinations) - 1):
    for checker in combinations:
        #checker = combinations[i + 1]
        for element in final_list:
            diff = sum(map(lambda x,y: bool(x-y),checker, element))
            #if (diff == d):
            if diff != d:
                break
        else:
            final_list.append(checker)
            print(final_list)
        
        #i += 1
    
    if (len(checker) >= M):
        result = True
        
    return result
    
print(nmdcode([1,2,5], 10, 200, 3))

从一个空的final_list开始

在组合上循环检查final_list中的条件是否失败

如果失败break,循环将跳过else

如果条件没有失败,则执行else块,将元素附加到final_list

开始时final_list是空的,因此循环直接进入else块,并将combinations的第一个元素附加到final_list

相关问题 更多 >