Search code examples
pythonloopssplitlist-comprehensionany

Check if words are spelled correctly in list


I've been given a dictionary with the following words:

dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal',
              'examine', 'indication', 'is', 'means', 'minutely', 'or', 'scrutinize',
              'sign', 'the', 'to', 'uncertain']

I'm trying to write a spellchecker that tells which words in an input sentence are spelled incorrectly.

The expected output is either:

A) print incorrectly spelled words each at a new line

or

B) only if all words are spelled correctly, print OK

Here's the code I've come up with so far:

dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal',
              'examine', 'indication', 'is', 'means', 'minutely', 'or',
              'scrutinize', 'sign', 'the', 'to', 'uncertain']  

text = input().split()
counter = 0

for x in text:
    if x not in dictionary:
        counter += 1
        print(x, end='\n')
    elif not counter:
        print("OK")

Two sample inputs and outputs were given as examples to the expected results:

Sample Input 1:

srutinize is to examene closely and minutely

Sample Output 1:

srutinize

examene

Sample Input 2:

all correct

Sample Output 2:

OK

Code works fine for input 1, but input 2 instead of printing OK is printing all correct instead of OK.


Solution

  • You are almost there with your updated code. You should just check the counter once after the loop has finished, instead of doing it for every word:

    for x in text:
        if x not in dictionary:
            counter += 1
            print(x, end='\n')
    
    if counter == 0:
        print("OK")
    

    There is also a fancier way of solving the problem using a list comprehension:

    text = input().split()
    
    typos = [word for word in text if word not in dictionary]
    if typos:
        print("\n".join(typos))
    else:
        print("OK")