Sadman Shahriar Dip
Sadman Shahriar Dip

Reputation: 29

Generate all possible combinations of elements in a list

I've been trying to create a script where every possible combination of a list will be printed [where (1,2) and (2,1) will be counted as different entry]. For example:

c = [1,2]
# do something magical
print(c with magical stuff) 
>>>[(1), (2), (1, 1), (1, 2), (2, 1), (2, 2)]

I've tried itertools.permutations. It shows output as >>> () (1,) (2,) (1, 2) (2, 1). However, it doesn't include (1, 1) and (2,2)

Any help will be hugely appreciated. I'm new to coding (I'm very fluent in printing "Hello World!" though :3)

Upvotes: 1

Views: 2439

Answers (4)

pylang
pylang

Reputation: 44485

Make combinations with replacement and then permute the results, keeping only unique results.

import itertools as it 


combs = it.chain.from_iterable(it.combinations_with_replacement(c, i) for i in range(1,3))
perms = it.chain.from_iterable([set(it.permutations(i)) for i in combs])
list(perms)
# [(1,), (2,), (1, 1), (1, 2), (2, 1), (2, 2)]

Upvotes: 0

3pitt
3pitt

Reputation: 941

There may be some built-in (or more likely numpy) packages that can do this for you, but it is an excellent exercises to do it yourself.

One question - are you interested exclusively in length-2 permutation, or do you want to write a function for arbitrarily long permutations?

Also, see: How to generate all permutations of a list in Python

Upvotes: 1

cs95
cs95

Reputation: 402483

Try itertools.product:

def foo(l):
    yield from itertools.product(l)
    yield from itertools.product(l, l)

for x in foo([1, 2]):
     print(x)

(1,)
(2,)
(1, 1)
(1, 2)
(2, 1)
(2, 2)

Note that the yield from syntax is available from python3.3 onwards.

Upvotes: 5

neuhaus
neuhaus

Reputation: 4094

Works for me:

c = [1,2]
for i in itertools.permutations(c):
     print i

yields

(1, 2)
(2, 1)

Upvotes: 1

Related Questions