2

I want to have all possible combinations of a string without repeating a letter unless it exist more than once. And here some examples to clarify the idea:

"421" --> ["421", "412", "214", "241", "124", "142"]
"601" --> ["601", "610", "016", "061", "106", "160"]
"131" --> ["131", "113", "311"]

2 Answers2

0

Try itertools.permutations and then use ''.join to combine the characters back into string:

from itertools import permutations

def permute(letters):
  p = permutations(letters)     #create permutations
  s = [''.join(i) for i in p]   #join as strings
  return list(set(s))           #return unique combinations
  

print(permute('431'))
print(permute('601'))
print(permute('131'))
['143', '134', '413', '431', '314', '341']
['160', '601', '016', '106', '610', '061']
['131', '113', '311']
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

you can use itertools

import itertools
letters = '421'
combinations = []
for i in range(len(letters)):
    combinations.extend([''.join(x) for x in itertools.permutations(letters, i + 1) if len(x) == len(letters)])

print(combinations)

baris
  • 48
  • 7