这是问题所在,也是我试图解决它的原因,但在调试之后,我意识到我的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))
这是修改后的工作代码
从一个空的
final_list
开始在组合上循环检查
final_list
中的条件是否失败如果失败
break
,循环将跳过else
块如果条件没有失败,则执行
else
块,将元素附加到final_list
开始时
final_list
是空的,因此循环直接进入else
块,并将combinations
的第一个元素附加到final_list
相关问题 更多 >
编程相关推荐