'Get all possible string combinations without repetition in python [duplicate]
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"]
Solution 1:[1]
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)
Solution 2:[2]
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']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | baris |
| Solution 2 |
