0

Say I wanted to find all the possible combinations of elements (not the number of possible combinations given by nCk but the combinations themselves.) Further, say I'm interested in all possible combinations given all possible k. For example

elems = [a,b,c,d] #k=1
com_2 = [(a,b),(a,c),(a,d),(b,c),(b,d),(c,d)] #k=2
com_3 = [(a,b,c),(a,b,d),(a,c,d),(b,c,d)] #k=3
com_4 = [(a,b,c,d)] #k=4

I'm wondering, is there a built in python function that could accomplish this? (Perhaps part of the set class.) If not, how would you write a function to accomplish this effect?

elems = ['a','b','c','d']
sets = []
for idx1 in range(len(elems)):
  for idx2 in range(idx1+1, len(elems)):
    sets.append((elems[idx1],elems[idx2]))

sets
>>>
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

This works only for k=2, when k is larger, I'll need to add another for loop dynamically. This makes me think that recursion might be appropriate, but I'm at a complete loss on how to move forward.

This question seems to hint at the right direction, though I'm not a C++ programmer, so it's not at all clear to me.

edit: Stumbled on How to get all possible combinations of a list’s elements? which answers my question. Feel free to close, mods

jbuddy_13
  • 902
  • 2
  • 12
  • 34
  • 1
    Look at [itertools](https://docs.python.org/3/library/itertools.html#itertools.combinations) – Mark Dec 26 '20 at 18:54
  • 1
    Duplicate of [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) – mkrieger1 Dec 26 '20 at 19:00
  • 1
    Just use the above answers with different values for `k` =) – ssp Dec 26 '20 at 19:03

0 Answers0