1

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?

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.