vendredi 28 février 2020

Get a random permutation of a word that is different from the word

I would like to get a random permutation of the letters of a word, if possible, else the word itself.

How can this be done efficiently?

This is what I have for now

from itertools import permutations
import random

word = 'some_word'
permutations = [''.join(permutation) for permutation in permutations(word)]
random.shuffle(permutations)
scrambled_word = word
for permutation in permutations:
    if permutation != word:
        scrambled_word = permutation
        break

Basically, I am just getting the first permutation of all the permutations of the word. I will be doing this operation for many word and I find this method inefficient. In general, it should be unnecessary to get all the permutations of a given word.

I had in mind that I could somehow have an iterable of random permutations from which I can just retrieve the first permutation. How can this be done in Python? The function permutations of itertools is an iterable, but the elements are not in a random order. I need a random permutation, so that it will not look like the original word.




Aucun commentaire:

Enregistrer un commentaire