user2091683
user2091683

Reputation: 47

Search inside dynamic array in python

I want to implement a code that loops inside an array that its size is set by the user that means that the size isn't constant.

for example: A=[1,2,3,4,5] then I want the output to be like this:

[1],[2],[3],[4],[5]
[1,2],[1,3],[1,4],[1,5]
[2,3],[2,4],[2,5]
[3,4],[3,5]
[4,5]
[1,2,3],[1,2,4],[1,2,5]
[1,3,4],[1,3,5]
and so on
[1,2,3,4],[1,2,3,5]
[2,3,4,5]
[1,2,3,4,5]

Can you help me implement this code?

Upvotes: 1

Views: 172

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

You need itertools.combinations:

Example:

>>> from itertools import combinations
>>> A = [1,2,3,4,5]
>>> for i in xrange(1, len(A)+1):
...     for c in combinations(A, i):
...         print c
...         
(1,)
(2,)
(3,)
(4,)
(5,)
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(2, 3)
(2, 4)
...
...
(2, 4, 5)
(3, 4, 5)
(1, 2, 3, 4)
(1, 2, 3, 5)
(1, 2, 4, 5)
(1, 3, 4, 5)
(2, 3, 4, 5)
(1, 2, 3, 4, 5)

Upvotes: 1

NPE
NPE

Reputation: 500257

From the itertools documentation:

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

If you don't want the empty set, it is easy to remove.

(I assume the line breaks in your example have no significance. If they do, please explain how.)

Upvotes: 3

Related Questions