【问题标题】:Find all possible permutations and combinations of given no. of elements in a list using Python找到给定编号的所有可能排列和组合。使用 Python 的列表中的元素
【发布时间】:2020-12-10 14:06:19
【问题描述】:

我需要找到给定元素的所有可能排列和组合,而不需要重复相同的对。

例如

list = [a,b,c]

想要的输出是

[(a),(b),(c),(a,b),(a,c),(b,a),(b,c),(c,a),(c,b),(a,b,c),(a,c,b),(b,a,c),(b,c,a),(c,a,b),(c,b,a)]

我尝试在 python 中使用itertools 来获得相同的输出对,但失败了。 使用itertools.permutations 输出是

[abc,acb,bac,bca,cab,cba]

使用itertools.combinations 输出是

[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]

错过了像(b,a)这样的配对 .

使用itertools.combinations_with_replacement 在对中给出重复元素,例如(a,a,a),(b,b,b),这是不可接受的。

所需的输出不应包含重复的对元素。

【问题讨论】:

    标签: python algorithm combinations permutation itertools


    【解决方案1】:

    permutations 允许您指定排列列表的长度:

    如果包含空集:

    permlist = []
    
    for i in range(len(mylist) + 1):
        permlist += itertools.permutations(mylist, i)
    

    如果排除空集:

    permlist = []
    
    for i in range(len(mylist)):
        permlist += itertools.permutations(mylist, i+1)
    

    【讨论】:

      【解决方案2】:
      answer = set()
      L = ['a', 'b', 'c']
      for i in range(len(L)+1):
          for c in itertools.combinations(L, i):
              for p in itertools.permutations(c):
                  answer.add(p)
      
      In [288]: answer                                                                                                                                                                                                                                                                
      Out[288]: 
      {(),
       ('a',),
       ('a', 'b'),
       ('a', 'b', 'c'),
       ('a', 'c'),
       ('a', 'c', 'b'),
       ('b',),
       ('b', 'a'),
       ('b', 'a', 'c'),
       ('b', 'c'),
       ('b', 'c', 'a'),
       ('c',),
       ('c', 'a'),
       ('c', 'a', 'b'),
       ('c', 'b'),
       ('c', 'b', 'a')}
      

      【讨论】:

      • 你不需要三个循环,也不需要set(它不会产生重复)。只需初始化answer = [] 并将两个内部循环替换为for p in itertools.permutations(L, i): answer.append(p)。给定长度的所有组合的所有全长排列已经等同于给定长度的所有排列。
      • @ShadowRanger:哦,是的!感谢您的提醒。显然,咖啡不起作用;)
      猜你喜欢
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      相关资源
      最近更新 更多