简体   繁体   中英

Looking through a text file

I've been trying to create a function which gives a hint to the user who plays hangman. The idea behind the function is that I'm having a list of 5k words plus and I need to sort it out through numerous indicators, such as the word should be the same as the pattern, if the pattern is a___le so the words that I should look for suppose to be in the same group and that if the user has numerous wrong letter it'll not consider the words whom includes this letters

I'm aware that I didn't do it in the most pythonic or elegant way but if someone can tell me what is going wrong here I'm always getting a empty list or a list containing the words with the same length but the other conditions are being constantly ignored.

def filter_words_list(words, pattern, wrong_guess_lst):
    """
    :param words: The words I received from the main function 
    :param pattern: the pattern of the word in seach such as p__pl_
    :param wrong_guess_lst: the set of wrong used letters of the users
    :return: the function returns the words which are much to the conditions.
    """
    list(wrong_guess_lst) # Since I am receiving it as a set I'm converting it to a list.
    words_suggestions = [] # The list I'd like to put my suggested words.
    for i in range(0, len(words)): # First loop matching between the length of the patterns and the words
        if len(words[i]) == len(pattern):
            for j in range(0, len(pattern)):
                if pattern[j] != '_':
                    if pattern[j] == words[i][j]: # Checking if the letters of the words are a much.
                        for t in range(0, len(wrong_guess_lst)):
                         if wrong_guess_lst[t] != words[i][j]: # Does the same as before but only with the wrong guess lst.
                            words_suggestions.append(words[i])
    return words_suggestions

I think this is what you are looking for (explanation in code comments):

def get_suggestions(words: list, pattern: str, exclude: list) -> list:
    """Finds pattern and returns all words matching it."""
    # get the length of the pattern for filtering
    length = len(pattern)
    # create a filtered generator so that memory is not take up;
    # it only give the items from the word list that match the
    # conditions i.e. the same length as pattern and not in excluded words
    filter_words = (word for word in words
                    if len(word) == length and word not in exclude)
    # create a mapping of all the letters and their corresponding index in the string
    mapping = {i: letter for i, letter in enumerate(pattern) if letter != '_'}
    # return list comprehension that is made of words in the filtered words that
    # match the condition that all letters are in the same place and have the same
    # value as the mapping
    return [word for word in filter_words
            if all(word[i] == v for i, v in mapping.items())]


word_list = [
    'peach', 'peace', 'great', 'good', 'food',
    'reach', 'race', 'face', 'competent', 'completed'
]
exclude_list = ['good']
word_pattern = 'pe___'

suggestions = get_suggestions(word_list, word_pattern, exclude_list)
print(suggestions)
# output:
# ['peach', 'peace']


# a bit of testing
# order of items in the list is important
# it should be the same as in the word_list
patterns_and_answers = {
    '_oo_': ['food'],  # 'good' is in the excluded words
    '_omp_____': ['competent', 'completed'],
    '__ce': ['race', 'face'],
    'gr_a_': ['great'],
    '_a_e': ['race', 'face'],
    '_ea__': ['peach', 'peace', 'reach']
}

for p, correct in patterns_and_answers.items():
    assert get_suggestions(word_list, p, exclude_list) == correct
print('all test cases successfull')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM