Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

problem with itertools permutations in combination with english_words_set in a for loop

I want to get all possible words with 5,6,7 characters from a random string: word="ualargd"

I do the following:

  • A for loop to change the length of my permutations.
for i in range(5,len(word)+1):
    mywords=permutations(word, i)
  • The items created by the permutation get compared with an english dictionary set.

This works fine as long as i dont use the for loop.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The for loop creates the permutations mywords correctly. Once it contains strings like "aura" with 4 letters in the next loop "gudar" with 5 letters…

But unfortunately as soon as my loop leaves the first loop no word gets found anymore in the english dictionary. How come? If i replace the i value by hand in mywords=permutations(word, i) everything works fine.

#output     #expected output
5           5   
neeld       neeld
dense       dense
leden       leden
neele       neele
neese       neese
needs       needs
6           6
7           lendee
            needle
            selene
            lensed
            sendee
            7
            needles

The code for reproduction looks like this:

from itertools import permutations
from english_words import get_english_words_set

word="dseeenl"
web2lowerset = get_english_words_set(['web2'], lower=True)

for i in range(5,len(word)+1):
    print(i)
    mywords=permutations(word, i)
    for item in set(mywords):
        word=''.join(item)
        if word in web2lowerset:
            print(word)

>Solution :

Use a different variable name in the loop other than word, because you overwrite your original starting word

from itertools import permutations
from english_words import get_english_words_set

word="dseeenl"
web2lowerset = get_english_words_set(['web2'], lower=True)

for i in range(5,len(word)+1):
    print(i)
    mywords=permutations(word, i)
    for item in set(mywords):
        w=''.join(item)
        if w in web2lowerset:
            print(w)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading