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"]
1
  • What have you tried so far? Are you getting an error in your current code? Commented Jan 28, 2022 at 9:02

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.