我的任务是生成所有可行的方法,根据给定人数来分组给定数量的人。例如,如果共有4个人,对于包含2个人的组,我必须得到这样的数组:
ResultArr = {0: [1,2], 1:[1,3], 2:[1,4], 3:[2,3], 4:[2,4], 5:[3,4]}
我有这段代码:
elNum = 3 #Number of guys in one group
elLimit = 5 #Number of all guys
CheckArr = [1] * elNum
ResultArr = {}
ResultArr[0] = [-1] * elNum
goodCheckArr = [1] * elNum
for i in range(1, elNum+1):
ResultArr[0][i-1] = i
Checking = True
lenResultArr = 1
while Checking:
checkable = True
for i in range(0, elNum):
for ii in range(0, elNum): #
if (CheckArr[i] == CheckArr[ii]) and not i == ii:
checkable = False
if checkable:
status2 = [0]*lenResultArr
for i1 in range(0, len(ResultArr)):
print " "
print "ResultArr[",i1,"] = ", ResultArr[i1]
status1 = [0]*elNum
for i2 in range(0, elNum):
for i3 in range(0, elNum):
if ResultArr[i1][i2] == CheckArr[i3]:
status1[i2] = 1
print "status1 = ", status1, " ChechArr = ", CheckArr
if sum(status1) == elNum:
status2[i1] = 1
print "status2[",str(i1),"] = ", status2[i1]
if sum(status2) == 0:
goodCheckArr = CheckArr
ResultArr[lenResultArr] = goodCheckArr
lenResultArr = lenResultArr + 1
print "**** ResultArr = ", ResultArr
print "sum(status2) = 0 len(ResultArr) = ", str(len(ResultArr)), " lenResultArr = ", str(lenResultArr)
else:
print "sum(status2) > 0 len(ResultArr) = ", str(len(ResultArr)), " lenResultArr = ", str(lenResultArr)
print "************************************************************"
print "***",ResultArr
CheckArr[elNum-1] = CheckArr[elNum-1] + 1
for i in range(elNum-1, -1, -1):
if CheckArr[i] > elLimit:
CheckArr[i-1] = CheckArr[i-1] + 1
CheckArr[i] = 1
Checking = False
else:
Checking = True
print "************************************************************"
print "***",ResultArr
我认为问题出现在最后一段代码中:
print "************************************************************"
print "***",ResultArr
CheckArr[elNum-1] = CheckArr[elNum-1] + 1
for i in range(elNum-1, -1, -1):
if CheckArr[i] > elLimit:
CheckArr[i-1] = CheckArr[i-1] + 1
CheckArr[i] = 1
Checking = False
else:
Checking = True
print "************************************************************"
print "***",ResultArr
输出如下:
************************************************************
*** {0: [1, 2, 3], 1: [1, 2, 4]}
************************************************************
*** {0: [1, 2, 3], 1: [1, 2, 5]}
我不知道为什么变量检查的新元素会在结果数组中出现。
答案 0 :(得分:1)
您可以使用以下代码获取长度为2的所有组合。
import itertools
persons = [1, 2, 3, 4]
comb = itertools.combinations(persons, 2)
for i in comb:
print i
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)