假设我有一些整数1-10我如何根据1,2,3和4组对它们进行排序,它们不能与已经分组的整数组合在一起。 例如 (1,2,3)#1 2和3不能再相互配对 (4,5,6)#4 5和6不能再相互配对 (7,8,9)#7 8和9不能再相互配对 但现在... (1,4,7)有效 (2,5,8)有效 (3,6,9)作品
每当我尝试编写这样的程序时,我最终得到(1 2)(3 4)(5 6)(1 3)(1 4)(1 5)(1 6)(2 3)(2) 4)(2 5)(2 6)(3 5)(3 6)所有这些分区都是正确的但是一旦我以三人为一组工作,我的答案就变成了(0 1 2)(0 1 3)(0 1) 4)但0和1只能配对一次。
这是我的一组2的代码!数字0-3
def combinations2():
count = 0
count2 = 1
array = []
while(count < 4):
count2 = count + 1
while(count2 < 4):
temp = "(" + str(count) + " " + str(count2)+ ")"
array.append(temp)
#print(temp)
count2 += 1
count += 1
print(array)
combinations2()
答案 0 :(得分:0)
查看itertools。
from itertools import combinations
#this is the list of digits to consider
my_numbers = range(1,10)
def make_groups(n):
#initialize a couple lists for groups that we want, my_groups,
# and a list to keep track of pairs that we've already included
my_groups = []
pairs_seen = []
#get all combinations of size n of our digits
size_n_combins = combinations(my_numbers,n)
#for each combination to see if it meets our condition that each pair contained
# should not be in any of our other groups, if it does keep track of the pairs it
# contains and keep track of the combination by adding it to my_groups
for combin in size_n_combins:
if all([pair not in pairs_seen for pair in combinations(combin,2)]):
pairs_seen += [pair for pair in combinations(combin,2)]
my_groups.append(combin)
else:
continue
#finally return the groups we wanted
return my_groups
如果您致电make_groups(3)
,则会返回:
[(1, 2, 3), (1, 4, 5), (1, 6, 7), (1, 8, 9), (2, 4, 6), (2, 5, 7), (3, 4, 7), (3, 5, 6)]