9

Lets say I have an array called arr = [1,2,3,4]

How can I generate all the possible combinations with minimum 2 arguments that end up looking like

[1,2]
[1,3]
[1,4]
[1,2,3]
[1,2,4]
[1,2,3, 4]
[2,3]
[2,4]

and so on and so forth? Nothing Im trying works. I cant seem to use itertools.combinations or permutations because I need to know the argument size and I cant seem to use itertools.products because that will take minimum one argument from each of a list of lists that looks like this [[1],[2],[3],[4],[5]]. Extra thanks for one liners and comprehensions.

If I wanted to add them all together would that be too much to ask in terms of help? ;-)

That1Guy
  • 7,075
  • 4
  • 47
  • 59
Leon
  • 5,701
  • 3
  • 38
  • 38

2 Answers2

22

How about:

(x for l in range(2, len(arr)) for x in itertools.combinations(arr, l))

or

[x for l in range(2, len(arr)) for x in itertools.combinations(arr, l)]

if you need the list.

This is the equivalent of the following nested loop

res = []
for l in range(2, len(arr)):
    for x in itertools.combinations(arr, l):
        res.append(x)
return res
hivert
  • 10,579
  • 3
  • 31
  • 56
  • +1 for list comprehension. Do you mind telling me how this works though? This isnt a nested loop right? – Leon Jul 16 '13 at 21:16
1

From : http://wiki.python.org/moin/Powerful%20Python%20One-Liners use following to create all subsets and then refine those with length less than 2

f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j) & 1] for i in range(2**len(set(x)))]

print [k for k in f([1,2,3,4]) if len(k) >1]
Archit Jain
  • 2,154
  • 1
  • 18
  • 32