Search code examples
pythoncrossword

Find Possible word by its known letters and letters position


I'm attempting to find a word by its known letters and letters position (similar to a crossword) similar to what crosswordsolver.org does

Example :

input: 
B E _ K

possible words: 
BEAK
BECK
BELK
BERK

I have all possible words (with the same length) in a list. the problem is, i can't find a proper solution to compare user_input to my list.

comparing each index of each word on dictionary to user_input word letters seems to be a solution, however it is not efficient at all.

is there any other way to approach this problem ?

thank you in advance

EDIT : I should add that regex cannot be used as a solution because I'm working with Persian(farsi) words, which uses persian alphabet (similar to arabic)

User input is taken letter by letter and is stored as List. There might be more than 1 missing letter and theWord length can be anything between 1-10


Solution

  • A quick hack

    # Save pattern as (char, position) where position starts at 0
    pattern = [("B", 0), ("E", 1), ("K", 3)] 
    
    dictionary = ["BEAK", "BECK", "BELK", "BERK"]
    
    def match(word, pattern):
        if len(pattern) > len(word):
            return false
    
        return all(word[pos] == c for (c, pos) in pattern):
    
    def list_matches(pattern, dictionary):
        for word in dictionary:
            if match(word, pattern):
                print(word)
    
    list_matches(pattern, dictionary)
    

    You can use a Trie data structure and that will be much more efficient.