【问题标题】:Permutations with repetition in PythonPython中的重复排列
【发布时间】:2013-01-15 01:19:46
【问题描述】:

我想遍历大小为 1 的 n 维立方体的所有顶点。我知道我可以使用 itertools.product 做到这一点,如下所示:

>>> n = 3
>>> for j in it.product((0,1), repeat=n) :
...     print j
... 
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

但是我需要对每个顶点进行不同的处理,具体取决于在其坐标中找到的1s 的数量,即(0, 1, 1)、(1, 0, 1) 和(1, 1, 0) 都会收到相同的处理,因为它们都有两个1s。而不是使用上面的迭代器,然后计算1s 的数量,我想生成按1s 数量排序的笛卡尔积,类似于:

>>> for ones in xrange(n) :
...     for seq in magic_expression(ones, n) :
...         print ones, seq
... 
0 (0, 0, 0)
1 (0, 0, 1)
1 (0, 1, 0)
1 (1, 0, 0)
2 (0, 1, 1)
2 (1, 0, 1)
2 (1, 1, 0)
3 (1, 1, 1)

我的高中数学老师会将这些称为一次采用n 的两个元素的排列,其中第一个元素重复n - ones 次,第二个元素重复ones 次 ,很容易证明有n! / ones! / (n - ones)!个。

根据wikipedia,我可以按字典顺序生成它们,如下所示:

def lexicographical(ones, n) :
    perm = [0] * (n - ones) + [1] * ones
    yield tuple(perm)
    while True :
        k = None
        for j in xrange(n - 1) :
            if perm[j] < perm[j + 1] :
                k = j
        if k is None :
            break
        l = k + 1
        for j in xrange(k + 2, n) :
            if perm[k] < perm[j] :
                l = j
        perm[k], perm[l] = perm[l], perm[k]
        perm[k+1:] = perm[-1:k:-1]
        yield tuple(perm)

但是在时间上,这只会开始对 n &gt;= 10 的完整笛卡尔积进行计算,然后仅计算 ones &lt; 2,这不是典型的用例。有没有一种优雅的方式来加速我上面的代码,也许是一些强大的itertools voodoo,或者完全使用不同的算法?如果它有什么不同,我就不会关心产生的排列的顺序。还是我应该听天由命?


编辑

我对建议的解决方案做了一些计时。以itertools.product 的顺序使用顶点生成它们,计数总是最快的。但是要让它们按个数排序,Eevee 的列表排序解决方案是 n &lt;= 6 最快的,从那时起 Cam 的解决方案是两者中最快的。

我接受了 Cam 的解决方案,因为它更好地回答了所提出的问题。但就我将在我的代码中实现的内容而言,我将让自己去计算。

【问题讨论】:

    标签: python algorithm permutation


    【解决方案1】:

    如果您编写了超过 8 行代码来生成八个常量值,则说明出了问题。

    不只是嵌入我想要的列表,我会用愚蠢的方式来做:

    vertices = (
        (v.count(1), v)
        for v in itertools.product((0, 1), repeat=3)
    )
    for count, vertex in sorted(vertices):
        print vertex
    

    除非您使用 1000 个超立方体,否则您不应该担心任何巨大的性能问题。

    【讨论】:

      【解决方案2】:

      一种(低效的)替代方法:

      >>> ['{0:03b}'.format(x) for x in range(8)]
      ['000', '001', '010', '011', '100', '101', '110', '111']
      

      或者作为元组:

      >>> [tuple(int(j) for j in list('{0:03b}'.format(x))) for x in range(8)]
      
      [(0, 0, 0),
       (0, 0, 1),
       (0, 1, 0),
       (0, 1, 1),
       (1, 0, 0),
       (1, 0, 1),
       (1, 1, 0),
       (1, 1, 1)]
      

      按顶点数排序:

      >>> sorted(_, key=lambda x: sum(x))
      
      [(0, 0, 0),
       (0, 0, 1),
       (0, 1, 0),
       (1, 0, 0),
       (0, 1, 1),
       (1, 0, 1),
       (1, 1, 0),
       (1, 1, 1)]
      

      或者使用itertools:

      >>> sorted(itertools.product((0, 1), repeat=3), key=lambda x: sum(x))
      
      [(0, 0, 0),
       (0, 0, 1),
       (0, 1, 0),
       (1, 0, 0),
       (0, 1, 1),
       (1, 0, 1),
       (1, 1, 0),
       (1, 1, 1)]
      

      【讨论】:

        【解决方案3】:

        对于您的 3d 立方体用例,Eevee 的解决方案是正确的。

        不过,为了好玩和展示 itertools 的强大功能,这里有一个线性时间解决方案,它可以推广到更高的维度:

        from itertools import combinations
        
        # n is the number of dimensions of the cube (3 for a 3d cube)
        def generate_vertices(n):
            for number_of_ones in xrange(0, n + 1):
                for location_of_ones in combinations(xrange(0, n), number_of_ones):
                    result = [0] * n
                    for location in location_of_ones:
                        result[location] = 1
                    yield result
        
        for vertex in generate_vertices(3):
            print vertex
        
        
        # result:
        # [0, 0, 0]
        # [1, 0, 0]
        # [0, 1, 0]
        # [0, 0, 1]
        # [1, 1, 0]
        # [1, 0, 1]
        # [0, 1, 1]
        # [1, 1, 1]
        

        【讨论】:

        • 不错!这就是我一直在寻找的东西。 set这个操作不是没必要吗?
        • @Jaime:不,因为集合具有恒定的时间访问权限,这是下面部分所需要的。但是,您提出了一个很好的观点,那就是该部分有点冗长。我已将其更新为更清晰,可能更快
        • 我的原始解决方案供您参考:gist.github.com/4536013
        【解决方案4】:

        根据你对顶点的处理来计算并不是一个坏主意,因为如果你必须遍历所有这些顶点,O(f(n)) 至少是 O(f(n)*2 n),对它们进行排序是 O(n*2n)。所以这基本上取决于 f(n) 专业是否为 n。

        除此之外,还有一个可能的魔术表达式:

        def magic_expression(ones, n):
            a = (0,) * (n - ones) + (1,) * ones
            previous = tuple()
            for p in itertools.permutations(a):
                if p > previous:
                    previous = p
                    yield p
        

        在permutations with unique values 的帮助下。

        这是有效的,因为 itertools.permutations 产生排序结果。请注意,a 最初是排序的,因为零在前。

        【讨论】:

        • 这并不能解决问题。它要求一种方法来遍历按个数排序的立方体的顶点 - 这不是这样做的。
        • 虽然不是最好的解决方案,但这可以满足问题的 magic_expression 的预期,当与 for ones in xrange(3): ... 结合使用时将产生预期的输出。
        • 糟糕!确实如此。感谢您的澄清。
        【解决方案5】:

        以下是一些比 Cam 或 Eevee 运行得更快(对于中等 n)和几倍(对于大型 n)的代码。接下来是时间比较。

        def cornersjc (n):   # Re: jw code
            from itertools import product
            m = (n+1)/2
            k = n-m
            # produce list g of lists of tuples on k bits
            g = [[] for i in range(k+1)]
            for j in product((0,1), repeat=k):
                g[sum(j)].append(tuple(j))
            # produce list h of lists of tuples on m bits
            if k==m:
                h = g
            else:
                h = [[] for i in range(m+1)]
                for j in product((0,1), repeat=m):
                    h[sum(j)].append(tuple(j))
            # Now deliver n-tuples in proper order
            for b in range(n+1):  # Deliver tuples with b bits set
                for lb in range(max(0, b-m), min(b+1,k+1)):
                    for l in g[lb]:
                        for r in h[b-lb]:
                            yield l+r
        

        下面显示的计时结果来自 ipython 中的一系列%timeit 调用。每次通话的形式如
        %timeit [x for x in cube1s.f(n)]
        用名称 cornersjc, cornerscc, cornersec, cornerses 代替 f(代表我的代码、Cam 的代码、Eevee 的代码和我的 Eevee 方法的版本)和一个数字代替 n。

        n    cornersjc    cornerscc    cornersec    cornerses
        
        5      40.3 us      45.1 us      36.4 us      25.2 us    
        6      51.3 us      85.2 us      77.6 us      46.9 us    
        7      87.8 us      163 us       156 us       88.4 us    
        8     132 us       349 us       327 us       178 us    
        9     250 us       701 us       688 us       376 us    
        10    437 us      1.43 ms      1.45 ms       783 us
        11    873 us      3 ms         3.26 ms      1.63 ms
        12   1.87 ms      6.66 ms      8.34 ms      4.9 ms
        

        上面给出了cornersjc 的代码。 cornerscc、cornersec 和 cornerses 的代码如下。这些产生与cornersjc 相同的输出,除了 Cam 的代码产生一个列表列表而不是一个元组列表,并且在每个位计数组内产生相反的结果。

        def cornerscc(n):   # Re: Cam's code
            from itertools import combinations
            for number_of_ones in xrange(0, n + 1):
                for location_of_ones in combinations(xrange(0, n), number_of_ones):
                    result = [0] * n
                    for location in location_of_ones:
                        result[location] = 1
                    yield result
        
        def cornersec (n):   # Re:  Eevee's code
            from itertools import product
            vertices = ((v.count(1), v)
                        for v in product((0, 1), repeat=n))
            for count, vertex in sorted(vertices):
                yield vertex
        
        def cornerses (n):   # jw mod. of Eevee's code
            from itertools import product
            for vertex in sorted(product((0, 1), repeat=n), key=sum):
                yield vertex
        

        注意,cornersjc 的最后三行可以替换为

                    for v in product(g[lb], h[b-lb]):
                        yield v[0]+v[1]
        

        更干净但更慢。请注意,如果使用yield v 而不是yield v[0]+v[1],则代码运行速度比cornersjc 快,但是(n=5)会产生像 ((1, 0), (1, 1, 0) 这样的元组对结果));当使用yield v[0]+v[1] 时,代码运行速度比cornersjc 慢,但会产生相同的结果,如 (1, 0, 1, 1, 0) 的元组列表。 下面是一个示例时序,cornersjp 是修改后的cornersjc。

        In [93]: for n in range(5,13):
            %timeit [x for x in cube1s.cornersjp(n)]
           ....:     
        10000 loops, best of 3: 49.3 us per loop
        10000 loops, best of 3: 64.9 us per loop
        10000 loops, best of 3: 117 us per loop
        10000 loops, best of 3: 178 us per loop
        1000 loops, best of 3: 351 us per loop
        1000 loops, best of 3: 606 us per loop
        1000 loops, best of 3: 1.28 ms per loop
        100 loops, best of 3: 2.74 ms per loop
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-04-14
          • 1970-01-01
          • 2017-04-28
          • 1970-01-01
          • 1970-01-01
          • 2017-10-09
          • 1970-01-01
          相关资源
          最近更新 更多