【问题标题】:Set products in Python在 Python 中设置产品
【发布时间】:2011-03-17 08:40:56
【问题描述】:

集合 S 的 n 个副本的乘积表示为 Sn。例如,{0, 1}3 是所有 3 位序列的集合:

{0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1), (1,0,0),(1,0,1),(1,1,0),(1,1,1)}

在 Python 中复制这个想法的最简单方法是什么?

【问题讨论】:

  • 只是 {0,1} 还是其他什么?
  • 任意集合和任意 n 都很好。

标签: python math


【解决方案1】:

我想这行得通?

>>> s1 = set((0,1))
>>> set(itertools.product(s1,s1,s1))
set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)])

【讨论】:

    【解决方案2】:

    在 Python 2.6 或更高版本中,您可以将 itertools.product 与可选参数 repeat 一起使用:

    >>> from itertools import product
    >>> s1 = set((0, 1))
    >>> set(product(s1, repeat = 3))
    

    对于旧版本的 Python,您可以使用文档中的代码实现 product

    def product(*args, **kwds):
        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        pools = map(tuple, args) * kwds.get('repeat', 1)
        result = [[]]
        for pool in pools:
            result = [x+[y] for x in result for y in pool]
        for prod in result:
            yield tuple(prod)
    

    【讨论】:

      【解决方案3】:

      马克,好主意。

      >>> def set_product(the_set, n):
          return set(itertools.product(the_set, repeat=n))
      
      >>> s2 = set((0,1,2))
      >>> set_product(s2, 3)
      set([(0, 1, 1), (0, 1, 2), (1, 0, 1), (0, 2, 1), (2, 2, 0), (0, 2, 0), (0, 2, 2), (1, 0, 0), (2, 0, 1), (1, 2, 0), (2, 0, 0), (1, 2, 1), (0, 0, 2), (2, 2, 2), (1, 2, 2), (2, 0, 2), (0, 0, 1), (0, 0, 0), (2, 1, 2), (1, 1, 1), (0, 1, 0), (1, 1, 0), (2, 1, 0), (2, 2, 1), (2, 1, 1), (1, 1, 2), (1, 0, 2)])
      

      您还可以扩展 set 类型并使 __pow__ 方法执行此操作。

      【讨论】:

        【解决方案4】:
        print 'You can do like this with generator:'
        print set((a,b,c) for a in s1 for b in s1 for c in s1)
        

        【讨论】:

          猜你喜欢
          • 2018-07-23
          • 1970-01-01
          • 2016-01-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多