1

I'm using python (2.7.2) and I need all permutations without repetition from a list. More precisely,

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

correctly gives

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

But now I am looking for something would do the following

for i in myfunction([1,2,2]): print i
(1,2,2)
(2,2,1)
(2,1,2)

Whereas itertools would give that list twice (or, for ([1,1,1]) as the input, it is just repeated six times). This is basically something between itertools.permutations and itertools.combinations. I tried working with sets, but all solutions that I tried always created new problems and never matched the desired output.

6
  • 1
    Can't you just filter the result through a set? for i in set(itertools.permutations([1,2,2])): print i
    – tobias_k
    Commented Oct 27, 2016 at 15:33
  • Works. Thanks, somehow failed to get there in the beginning and ended up in way to complicated solutions. Commented Oct 27, 2016 at 15:41
  • 1
    There's an efficient way to do that in this old answer of mine
    – PM 2Ring
    Commented Oct 27, 2016 at 15:47
  • Impressive algorithm, but way above the demands of my program. Commented Oct 27, 2016 at 15:52
  • I'll add a modified version of that code here, since that question is somewhat different to yours.
    – PM 2Ring
    Commented Oct 27, 2016 at 15:52

1 Answer 1

3

It looks like you want the set.

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

Which gives:

{(1, 2, 2), (2, 2, 1), (2, 1, 2)}

Alternatively, without saving the objects to a variable:

for i in set(itertools.permutations([1,2,2])):
    print(i)
3
  • 1
    Is there any reason you don't just insert directly into the set? What is the purpose of the list? Commented Oct 27, 2016 at 15:38
  • I edited my response to include the direct method but the reason was to show how keep an object with the desired information.
    – Andy
    Commented Oct 27, 2016 at 15:40
  • Why would you need to save the objects? Commented Oct 27, 2016 at 15:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.