permutation de nombre sans doublon
Bonjour,
[Python 3.x]
:arrow: Problème:
Je cherche à générer toutes les permutations d'un nombre donné:
Code:
1 2 3 4 5 6 7 8 9 10 11
|
import itertools
def get_all_perms(n):
n_str = str(n)
perms = [int(''.join(x)) for x in list(itertools.permutations(n_str))]
return perms
if __name__ == '__main__':
perms = get_all_perms(123)
print(perms) |
Output:
Citation:
[123, 132, 213, 231, 312, 321]
Maintenant avec n=122
Citation:
[122, 122, 212, 221, 212, 221]
Alors que je cherche plutôt à obtenir (donc: liste sans doublon):
Citation:
[122, 212, 221]
Ce qui fonctionne avec ça:
Code:
1 2 3 4 5 6 7 8 9
|
def get_all_perms(n):
n_str = str(n)
perms = [int(''.join(x)) for x in list(itertools.permutations(n_str))]
out_perms = list()
for perm in perms:
if perm not in out_perms:
out_perms.append(perm)
return out_perms |
Mais ce dernier code me donne l’impression d'être suboptimal (deux listes utilisées, un parcours pour chaque liste, etc.).
:arrow: Est-il possible , à l'intérieur d'une 'list comprehension' d'ajouter une condition pour éviter qu'un élément soit ajouter s'il existe déjà dans la liste ?
:arrow: Quelqu'un aurait-il une idée pour un code propre concernant ce problème?
Merci beaucoup :D