-4

Given a list: Ex: [1,2,3,4].

Print the following: [], [1], [1,2], [1,2,3], [1,2,3,4], [2], [2,3], [2,3,4] and so on

Basically we need to get all the combinations.

M. K. Hunter
  • 1,778
  • 3
  • 21
  • 27
harshatba
  • 70
  • 8

3 Answers3

1

using itertools.combinations:

>>> import itertools
>>> my_list = [1,2,3,4]
>>> [ list(x) for i in range(len(my_list)+1) for x in itertools.combinations(my_list,i) ]
[[], [1], [2], [3], [4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]

if you want consecutive:

>>> [[]]+[ my_list[i:j] for i in range(len(my_list)) for j in range(i+1,len(my_list)+1) ]
[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

This post explains how: How to get all possible combinations of a list’s elements?

[[x for x in itertools.combinations([1,2,3,4], y)] for y in range(4)]

That will provide the answer. itertools.combinations([1,2,3,4], y) will provide all the combinations of y elements. range(4) will provide the range 1 through 4 The nested list comprehension iterates through the number of elements to combine and the combinations themselves.

The output is:

[[()],
 [(1,), (2,), (3,), (4,)],
 [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)],
 [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]]

Then we can flatten the list with chain.from_iterable, as stated in this post: Making a flat list out of list of lists in Python

list(itertools.chain.from_iterable([[x for x in itertools.combinations([1,2,3,4], y)] for y in range(4)]))

Final output:

[(), (1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
Community
  • 1
  • 1
M. K. Hunter
  • 1,778
  • 3
  • 21
  • 27
0

If your input values are always consecutive, you can try the following idea:

result = []

for i in xrange(1, 6):
    for j in xrange(1, 6):
        if i > j:
            result.append(range(j, i))

print [[]] + sorted(result)

Result:

[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
Akavall
  • 82,592
  • 51
  • 207
  • 251