1

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)

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 6
    But the output you showed _does_ both include `(1,2)` and `(2,1)`. – khelwood Aug 30 '17 at 15:31
  • Possible duplicate of [How to generate all permutations of a list in Python](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) – Ma0 Aug 30 '17 at 15:40

4 Answers4

5

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
1

Works for me:

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

yields

(1, 2)
(2, 1)
neuhaus
  • 3,886
  • 1
  • 10
  • 27
1

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

3pitt
  • 899
  • 13
  • 21
  • This does not really answer the question. – cs95 Aug 30 '17 at 15:40
  • @cᴏʟᴅsᴘᴇᴇᴅ it shows however that he is worthy of the 50 rep required for *commenting*. That is the reason I upvoted anyway. But Coldspeed is right Mike. This would be more appropriate as a comment, not an answer. – Ma0 Aug 30 '17 at 15:41
  • wasnt sure if it was appropriate to code up a beginner's example, opted to give some high level thoughts – 3pitt Aug 30 '17 at 15:41
0

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)]
pylang
  • 40,867
  • 14
  • 129
  • 121