0

I'm trying to create a list from a permutation of a str object. However the resultant list has duplicates. I have the following code:

from itertools import permutations
a = permutations('144')
b = [''.join(i) for i in a]
print(b) 

What am I doing wrong? I'm getting the following:

['144', '144', '414', '441', '414', '441']
Nj_W
  • 1
  • 1
  • 6
    Because your original elements have duplicates (two 4s) – khelwood May 03 '21 at 15:10
  • Easiest way to handle this may be to convert it to a `set` if the idea is that the str can have repeated characters. – astrochun May 03 '21 at 15:11
  • I would answer, but I think the answer is well documented here, although if your output is small, using set on the list to eliminate duplicates isn't a bad idea for simplicity. https://stackoverflow.com/questions/46895696/prevent-duplicates-from-itertools-permutations With this I think it's safe to say this question is a duplicate. – Grape Dragon May 03 '21 at 15:19

2 Answers2

2

No. That is the expected result because there are duplicate characters in your input string.

If all you are interested are the elements of the permutation then pass your list through set. If instead you NEED a list, pass it through list again

Example:

from itertools import permutations

a = permutations('144')
b = set(''.join(i) for i in a) 
c = list(set(''.join(i) for i in a)) # note that I've removed square brackets
print(b)
print(c)

Protip: use generator expressions wherever possible

1

You have duplicate elements (characters) in your string. The function permutations will not distinguish between them.

You will have no duplicates if you iterate the permutations of the set of the characters, e.g.:

from itertools import permutations
a = permutations(set('144'))
b = [''.join(i) for i in a]
print(b)

Or, if you want to iterate over the disctinct permutations of the string containing even duplicates of the same characters, you can use the set of the permutations, like:

from itertools import permutations
a = permutations('144')
b = [''.join(i) for i in set(a)]
print(b)
quantummind
  • 2,086
  • 1
  • 14
  • 20
  • `a=itertools.combinations_with_replacement(set("144"), 3)` incase the output has to be of three elements. `['444', '441', '411', '111']` – samusa May 03 '21 at 15:20
  • I don't think this is what the question is asking, using set on the characters makes the output [14, 41] instead of ['144', '414', '441']. – Grape Dragon May 03 '21 at 15:21
  • Yes, you are right. I have edited the answer to include a solution for the other target as well. – quantummind May 03 '21 at 15:27