【问题标题】:Coding theory - Algorithm编码理论 - 算法
【发布时间】:2021-12-04 21:37:56
【问题描述】:

这是问题和我试图解决的问题,但在调试后我意识到我的 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))


【问题讨论】:

  • 你怎么知道它不起作用?请参阅How to Ask 以及如何创建minimal reproducible example
  • @Lebcode 您的逻辑是错误的,当您循环 final_list 并计算 diff 时,每次差异都很好时,您重复附加相同的条目,如果每个差异,您只需要附加条目不错
  • 您可以将bool(x-y) 替换为x==y
  • 这个问题听起来不应该用蛮力来解决,而应该用组合论来解决。实际的输入列表根本不重要,只关心其中唯一项目的数量?
  • @nadapez 肯定是x != y?

标签: python algorithm theory


【解决方案1】:

这是修改后的代码

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

【讨论】:

  • 另一个错误:if (len(checker) &gt;= M): 应该是 if len(final_list) &gt;= M:
  • @user3386109 或者只是return (len(final_list) &gt;= M)
猜你喜欢
  • 2017-12-27
  • 2012-10-16
  • 1970-01-01
  • 2010-12-24
  • 2019-11-23
  • 2011-07-19
  • 2017-04-19
  • 1970-01-01
相关资源
最近更新 更多