我想编写一个代码来获取针对5个用户输入集的所有组合,其中每个输出子集仅匹配来自任何输入集的< = 3个元素。
示例:
userInput1=(a,b,c,d,e)
userInput2=(c,d,e,f,g)
userInput3=(f,g,h,i,j)
userInput4=(g,h,i,j,k)
userInput5=(k,l,m,n,o)
# Turn 5 lists into 1 large list with no duplicates
allEntries = list(set(userInput1 + userInput2 + userInput3 + userInput4 + userInput5 ))
# Generate all possible list combinations
allCombinations = list(itertools.combinations( allEntries,5))
print "All combinations:"
for subset in allCombinations:
?????????
print subset
如何进行此检查以限制重叠?例如,(g,i,j,k,o)失败,因为它与userInput4共享 4 元素。
E.g。 - 所有组合
(a,c,j,l,o)
(k,b,a,m,n)
答案 0 :(得分:0)
这不是一个使用 itertools 的简单解决方案。但是,您确实有正确的开始。现在,在生成它时检查每个列表:
check_set = [
set(userinput1),
set(userinput2),
set(userinput3),
set(userinput4),
set(userinput5)
]
for five in itertools.combinations( allEntries,5):
five_set = set(five)
# If there are no overlaps of more than 3 elements,
# accept the solution.
if !any(len(five_set.intersection(user_set)) > 3
for user_set in check_set):
print five
# ... or whatever you do to save the good combination.