[英]Build combinations without pair repetition
给定一个数据集,我想构建所有组合(仍然使用itertools.combinations
)。 减少组合数量n!/r!/(nr)!
我想省略其他组合中包含的对。
为了说明一个小例子。 所有combinations(range(9), 3)
看起来像
(0,1,2), (0,1,3), (0,1,4),... (0,1,8),... (0,7,8), (1,2,3),...
这使得(0,1)
对成为7个元组的一部分。 也适用于所有其他元组。
range(9), 3
完整输出:
(0, 1, 2)
(0, 3, 4)
(0, 5, 6)
(0, 7, 8)
(1, 3, 6)
(1, 4, 7)
(1, 5, 8)
(2, 3, 8)
(2, 4, 5)
(2, 6, 7)
(3, 5, 7)
(4, 6, 8)
给定n
元素的范围,构建长度为r
元组使用(n-1)*n/2
对,并应提供(n-1)*n/(r-1)/r
元组。
对于长度为3的元组
from numpy import roll
from pprint import pprint
def a(s):
if len(s)<3:return
s=list(s)
z=s.pop(0)
s1,s2=s[0::2],s[1::2]
l=[]
for a,b in zip(s1,s2):l+=[(z,a,b)]
z1,z2=s1.pop(0),s2.pop(0)
if(len(s1)>1 and len(s2)>1):
for a,b in sorted(map(sorted,zip(s1,roll(s2,-1)))):l+=[(z1,a,b)]
if(len(s1)>2 and len(s2)>2):
for a,b in sorted(map(sorted,zip(s1,roll(s2,1)))):l+=[(z2,a,b)]
if(len(s1)>3):l+=[a(s1)]
if(len(s2)>3):l+=[a(s2)]
return l
s = range(9)
pprint(a(s))
使用递归,我们可以构建各种长度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.