【问题标题】:How do I solve this permutation coding question? [duplicate]如何解决这个排列编码问题? [复制]
【发布时间】:2021-07-20 06:43:14
【问题描述】:

我记得在 Leetcode 中看到过一次,但不确定是哪一个。这就是问题所在。

我有一个列表['a','b','c']。并且通过排列,我希望得到与给定列表的各种可能列表组合的结果。

预期

result = [['a'],['b'],['c'],
          ['a','b'],['b','c'],['a','c'],
          ['a','b','c']]

如果['a','b','c','d'],应该是

result = [['a'],['b'],['c'],['d'],
          ['a','b'],['a','c'],['a','d'],['b','c'],['b','d'],['c','d'],
          ['a','b','c'],['a','b','d'],['a','c','d'],['b','c','d'],
          ['a','b','c','d'],
]

如果我能从你们那里得到任何启发,我将不胜感激。

【问题讨论】:

  • itertools 的文档中有一个powerset 配方。

标签: python combinations permutation


【解决方案1】:

您可以使用itertools.combinations 来实现:

from itertools import combinations

l = ['a', 'b', 'c', 'd']

c = [list(combinations(l, i)) for i in range(1, len(l) + 1)]
>>> c
[[('a',), ('b',), ('c',), ('d',)],
 [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')],
 [('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')],
 [('a', 'b', 'c', 'd')]]

【讨论】:

    【解决方案2】:

    这个问题需要你输出问题的幂集,所以输出中总会有2^n元素,'n'是初始列表中元素的数量,2^n将包括phi,所以循环的限制可能是2^n-1,您可以尝试迭代方法!

    附:我不给你答案,因为我觉得你想自己解决这个问题!

    【讨论】:

    • 谢谢!我会检查的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多