0

A file with approx. 127,000+ words is imported and put into a list

try:
    dictionary = open("dictionary.txt", "r")
except:
    print("Dictionary not found")
    exit()
list_of_words = [word.rstrip('\n').rstrip('\r') for word in dictionary]

When the user enters a word length it checks to make sure the word is within the parameters.

def length_check(x):
    while(1):
        x = int(input("Please enter a word length: "))
        if x >= 1 and x <=147:
            return
        else:
            print ('enter proper length')

it then takes that word length and checks it against the words in the list and deletes any word in the list, thats not equal to "word_length"

def read_and_delete(x):
    i = 0
    for removal in x:
        if len(x[i]) != word_length:
            del x[i]
            i += 1
        elif len(x[i]) == word_length:
            i += 1
        else:
            continue
    print(len(list_of_words))

But for some reason, the outputted result is exactly half of the words in the list and I cannot see why as there is no divide at all in the code.

MLJezus
  • 79
  • 1
  • 9

1 Answers1

0

You are doing the mistake of iterating through the list and modifying it in the same time. You should always avoid that.

In your code del[i] creates a gap and then shifts all the subsequent numbers in the array, left by one position to fill the gap. When you increment i, you skip an element.

For completeness, this would fix your code.

def read_and_delete(x):
    i = 0
    for removal in x:
        if len(x[i]) != word_length:
            del x[i]
        elif len(x[i]) == word_length:
            i += 1
        else:
            continue
    print(len(list_of_words))

Here is a better way of doing it

def read_and_delete(x):
    return [word for word in x if len(word) == word_length]

This returns a new list and does not change the previous one.

Andrei Cioara
  • 3,404
  • 5
  • 34
  • 62