python - Coding theory - Algorithm
问题描述
Here's the question and my attempt at solving it, but after debugging I realized that my while loop is not functioning as needed. Any help would be greatly appreciated.
Question: Given an alphabet q, create a list of combinations (with replacement) of size n from the alphabet. If there are at least M elements in the list of combinations, where each elements differs from the rest by d list items, return 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))
解决方案
这是修改后的代码
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
是空的,所以循环直接进入块并附加toelse
的第一个元素。combinations
final_list
推荐阅读
- opengl - glOrtho 的实际公式是什么
- fonts - Godot - 按需制作标签,并使用 GDscript 设置其字体大小
- powershell - 将值附加到 AD 组对象
- sql - 表被锁定时如何自动停止 PostgreSQL 查询?
- .net - Net Core 中“ProducesResponseType”的 .NET 等价物是什么?
- git - git docs - “上游”总是意味着“服务器端分支”吗?
- java - 处理多线程时如何避免瓶颈?
- javascript - 从函数返回的 API 响应返回未定义
- ios - 调用 Swift 协议初始化器
- javascript - 如果 props 改变,React Native 组件不会重新渲染