-1

Given a list l:

l = ['A', 'B', 'C']

How can I write a function that returns all possible unique combinations of n members, in a list of lists? Order doesn't matter for uniqueness. The outputs in this example would be (the order is also unimportant in the output):

my_function(list=l, n=1)

[['A'], ['B'], ['C']]

my_function(list=l, n=2)

[['A', 'B'], ['A', 'C'], ['B', 'C']]

my_function(list=l, n=3)

[['A', 'B', 'C']]
CHRD
  • 1,917
  • 1
  • 15
  • 38
  • Are you being asked to write a library method like itertools combinations? Or just being tasked with discovering that method? I suspect the former, but want to be sure. – JacobIRR Aug 04 '20 at 21:41
  • Not sure I understand your question! But I suspect the latter :) – CHRD Aug 04 '20 at 21:43
  • Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Pranav Hosangadi Aug 04 '20 at 21:45

2 Answers2

2

You can use itertools.combinations for the task:

from itertools import combinations

l = ['A', 'B', 'C']

def my_function(lst, n):
    rv = []
    for c in combinations(lst, n):
        rv.append(list(c))
    return rv

print(my_function(l, 1))
print(my_function(l, 2))
print(my_function(l, 3))

Prints:

[['A'], ['B'], ['C']]
[['A', 'B'], ['A', 'C'], ['B', 'C']]
[['A', 'B', 'C']]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • This question is a duplicate of [this one](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements). Why do [reputable people keep answering duplicates?](https://meta.stackoverflow.com/questions/357021/reputable-people-keep-answering-duplicates-whats-the-solution) – Pranav Hosangadi Aug 05 '20 at 15:09
0

Without Itertools:

a=['A','B','C']
def combi(a):

    result = [[]]
    for x in a:
       result.extend([subset + [x] for subset in result])
    return result
print(combi(a))
Addy
  • 417
  • 4
  • 13