0

I was trying to look for all the 7-letter words that can be made by rearranging the word 'PLANETS', as an exercise (I used the sowpods library downloaded from here: http://norvig.com/ngrams/sowpods.txt).

This is the code:

file_name = 'sowpods.txt'
a = open(file_name,'r')
b = a.read()
c = b.split('\n')
d = []

for corr in c:
    if len(corr) == 7:
        d.append(corr)
        
for corr in d:
    m = 0
    while m < 7:
        if (corr[m] == 'P' or corr[m] == 'L' or corr[m] == 'A' or corr[m] == 'N' or corr[m] == 'E' or corr[m] == 'T' or corr[m] == 'S'):
            pass
        else:
            d.remove(corr)
            break
        m += 1
print(d)

The program ran without any error messages, but it didn't remove many words that I expected it to, even though it removed other similar words, for example, it removed the word 'ZORILLA' but not 'ZORILLE'. I am not sure why it did that. Could someone please explain, and suggest some changes to the code?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

0

Deleting an item from a list you are iterating over will confuse the iteration. Just blank out the item instead, or iterate over the list in reverse.

Mario Camilleri
  • 1,457
  • 11
  • 24