How to check if a few letters are part of a real word in python

54 Views Asked by At

I'm making a boggle checker, where you input the 16 letters given in the boggle game, and the python program gives you all the possible words. The algorithm I am using is that it goes to the first letter and checks all adjacent letters to see if it is part of a real word. If yes it checks all the adjacent letters of that letter and repeats until it has found a full word. Then it repeats this entire process, but starting from the second letter. It will do this process 16 times. Then it will output all the words found. However, how do i check if the letters so far are part of a word. e.g. A, then T, then T. How do i chekck if that is part of a word and i should carry on, or if its not part of a real word and it should stop, or if it is the full word and stop. Also it has to be that you don't check if these letters are part of a certain word, it has to check it has to see if it is part of any word unspecified

I havent been able to try anything as i'm not sure what to do.

2

There are 2 best solutions below

5
John Gordon On

Assuming you have a list of legal words and a partial guess:

allwords = ["aardvark", "able", ...]
guess = "att"

for word in allwords:
    if word.startswith(guess):
        # this guess is part of a word, so stop looking
        break
else:
    # the loop ran to completion, so guess did not match any legal word
0
Oskar Hofmann On

If your partial word you are testing is the first letters of a potential word, you can use the solution of @JohnGordon. If these letters might be somewhere in the word, you can test via in:

words = ['doggo', 'cat']
guess = 'ogg'

for word in words:
    if guess in word:
        # do something