如何在Python2.7中使用itertool根据用户输入控制所有组合子集
我想编写一个代码,以获得针对5个用户输入集的所有组合,其中每个输出子集仅匹配,这不是使用itertools的简单解决方案。但是,您确实有一个正确的开始。现在,在生成每个列表时检查它:如何在Python2.7中使用itertool根据用户输入控制所有组合子集,python,python-2.7,Python,Python 2.7,我想编写一个代码,以获得针对5个用户输入集的所有组合,其中每个输出子集仅匹配,这不是使用itertools的简单解决方案。但是,您确实有一个正确的开始。现在,在生成每个列表时检查它: check_set = [ set(userinput1), set(userinput2), set(userinput3), set(userinput4), set(userinput5) ] for five in iterto
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.
为什么您的第一个输出不是
a、b、c、f、g
,它将匹配第一个userInput
中的三个整数,以及其他两个或更少的整数set
ifying无疑会降低输出的可预测性,因此为了确保我所描述的结果,您需要定义allEntries
:allEntries=sorted(set(userInput1+userInput2+userInput3+userInput4+userInput5))
以使输出具有可预测的顺序。我认为没有简单的方法可以做到这一点,毕竟,当您创建“大列表”时,有关来源的信息会丢失。您可能需要手动检查每个组合是否包含任何输入列表中的3个以上。
(a,c,j,l,o)
(k,b,a,m,n)
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.