构建组合而不重复对

时间:2017-10-30 09:46:26

标签: python optimization combinations itertools

给定数据集我想构建所有组合(仍然使用$scope.getArray)。 要减少组合数itertools.combinations,我想省略其他组合中包含的对。

举例说明一个小例子。所有n!/r!/(n-r)!看起来都是

combinations(range(9), 3)

这使得(0,1,2), (0,1,3), (0,1,4),... (0,1,8),... (0,7,8), (1,2,3),... 对成为7元组的一部分。也适用于所有其他元组。

(0,1)的完全通缉输出:

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) 元素的情况下,使用r元素构建长度为n的元组,并且应提供(n-1)*n/2元组。

  1. 如何构建输出?
  2. 如何科学地命名这个“结合省略”的东西?

1 个答案:

答案 0 :(得分:0)

长度为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))

使用递归我们可以构建各种长度

相关问题