0
from itertools import combinations
a = [1,2,3]
combinations(a,2) #will give me ((1,2),(1,3),(2,3))
combinations(a,3) #will give me ((1,2,3),)

but what if I want results of different length which is in a array e.g.

I want to find all combinations of given array[1,2,3] of length more than or equal to 2 so result should be ((1,2),(1,3),(2,3),(1,2,3))

something like c = combinations(a,>=2) I tried to use lambda but its not working

c = combinations(a,lambda x: x for x in [2,3])

as well list comprehensive c = combinations(a,[x for x in [2,3]])

I know I can use a simple loop and then find out the combinations of diff length.

for l in [2,3]:
    combinations(a,l)

But Is there any pythonic way to do this?

user3745956
  • 33
  • 2
  • 6

1 Answers1

4

You could combine combinations and chain.from_iterable:

>>> from itertools import chain, combinations
>>> a = [1,2,3]
>>> n = 2
>>> cc = chain.from_iterable(combinations(a, i) for i in range(n, len(a)+1))
>>> list(cc)
[(1, 2), (1, 3), (2, 3), (1, 2, 3)]

chain.from_iterable here is flattening what the generator expression (combinations(a, i) for i in range(n, len(a)+1)) is producing. Otherwise you'd wind up with something like

>>> [list(combinations(a,i)) for i in range(n, len(a)+1)]
[[(1, 2), (1, 3), (2, 3)], [(1, 2, 3)]]

which is fine, but not quite in the format you were looking for.

DSM
  • 342,061
  • 65
  • 592
  • 494