【问题标题】:Find all combinations with i 0s and (n-i) 1s in array of size n.在大小为 n 的数组中查找所有包含 i 0 和 (n-i) 1 的组合。
【发布时间】:2013-08-30 16:42:14
【问题描述】:

我一直在尝试使用 itertools.product() 和 itertools.permutations() 来解决这个问题,但仍然找不到我需要的组合。抱歉,如果以前有人问过这个问题,但我到处搜索都无济于事。

例如,给定一个大小为 6 的字节数组,我怎样才能轻松地遍历所有可能包含 2 个 0 和 4 个 1 的集合?即,以下序列(希望我是对的):

  • 001111
  • 010111
  • 011011
  • 011101
  • 011110
  • 100111
  • 101011
  • 101101
  • 101110
  • 110011
  • 110101
  • 110110
  • 111001
  • 111010
  • 111100

我知道序列的大小将是 n!/((n-i)!*i!),但我无法通过迭代单个组合来解决我的问题。我将使用最大为 10,000 的数组,因此循环所有可能的“01”排列并丢弃不适合的数组对我来说效率太低。输出的顺序也无关紧要。

【问题讨论】:

    标签: python combinations combinatorics


    【解决方案1】:
    >>> from itertools import combinations
    >>> seq_len = 6
    >>> _0_count = 2
    >>> positions = range(seq_len)
    >>> _0_positions = combinations(positions, _0_count)
    >>> [[0 if i in zpos else 1 for i in positions] for zpos in _0_positions]
    [[0, 0, 1, 1, 1, 1],
     [0, 1, 0, 1, 1, 1],
     [0, 1, 1, 0, 1, 1],
     [0, 1, 1, 1, 0, 1],
     [0, 1, 1, 1, 1, 0],
     [1, 0, 0, 1, 1, 1],
     [1, 0, 1, 0, 1, 1],
     [1, 0, 1, 1, 0, 1],
     [1, 0, 1, 1, 1, 0],
     [1, 1, 0, 0, 1, 1],
     [1, 1, 0, 1, 0, 1],
     [1, 1, 0, 1, 1, 0],
     [1, 1, 1, 0, 0, 1],
     [1, 1, 1, 0, 1, 0],
     [1, 1, 1, 1, 0, 0]]
    

    注意:这可以简化为单行,但您会丢失有意义的名称。为了节省内存,将外部列表推导式更改为生成器表达式。

    【讨论】:

      【解决方案2】:

      怎么样:

      positions = range(1, 7)
      itertools.combinations(positions, 4)
      

      这将为您提供所需的所有1 职位组合。

      【讨论】:

        猜你喜欢
        • 2022-01-13
        • 2020-01-09
        • 1970-01-01
        • 2019-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        相关资源
        最近更新 更多