0

I remember seeing it once in Leetcode but not sure which one. Here's the problem.

I have a list ['a','b','c']. And through permutation, I want to have a result of all kinds of possible list combinations with the give list.

Expected

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

if ['a','b','c','d'], it should be

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'],
]

I would really appreciate if I can get any inspiration from you guys.

  • There is a [`powerset`](https://docs.python.org/3/library/itertools.html#itertools-recipes) recipe in the documentation of `itertools`. – Matthias Jul 20 '21 at 07:25

2 Answers2

2

You can use itertools.combinations to accomplish that:

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')]]
Corralien
  • 109,409
  • 8
  • 28
  • 52
1

This problem requires you to output the power-set of the problem, so there will always be 2^n elements in the output, with 'n' being the number of elements in the initial list, and 2^n will include phi, so perhaps the limit for the loop will be 2^n-1, you could try an iterative approach!

P.S. I am not giving you the answer since I feel that you want to solve this problem on your own!