从单词列表中查找给定句子的字谜

Find anagrams of a given sentence from a list of words

我有一个句子没有空格,只有小写字母,例如:

"johndrinksmilk"

和一个单词列表,其中只包含可能是上面句子的字谜的单词,而且这些单词是按字母顺序排列的,例如:

["drink","drinks","john","milk","milks"]

我想创建一个函数 (不使用库),其中 return 是三个单词的元组,它们一起可以构成给定句子的字谜。这个元组必须是句子的最后一个可能的字谜。如果给定列表中的词不能用来构成给定的句子,函数应该 return None。因为我知道我很不擅长解释事情,所以我会尝试给你一些例子:

例如:

sentence = "johndrinksmilk"
g_list = ["drink","drinks","john","milk","milks"]

结果应该是:

r_result = ("milks","john","drink")

虽然这些结果应该是错误的:

w_result = ("drinks","john","milk")
w_result = None
w_result = ("drink","john","milks")

我试过这个:

def find_anagram(sentence, g_list):     
g_list.reverse()
for fword in g_list:       
    if g_list.index(fword) == len(g_list)-1:
        break
    for i in range(len(fword)):
        sentence_1 = sentence.replace(fword[i],"",1)
    if sentence_1 == "":
        break
    count2 = g_list.index(fword)+1
    for sword in g_list[count2:]:
        if g_list.index(sword) == len(g_list)-1:
            break
        for i in range(len(sword)):
            if sword.count(sword[i]) > sentence_1.count(sword[i]):
                break
            else:
                sentence_2 = sentence_1.replace(sword[i],"",1)
        count3 = g_list.index(sword)+1
        if sentence_2 == "":
            break
        for tword in g_list[count3:]:
            for i in range(len(tword)):
                if tword.count(tword[i]) != sentence_2.count(tword[i]):
                    break
                else:
                    return (fword,sword,tword)
return None

但不是 returning:

("milks","john","drink")

它returns:

None

谁能告诉我怎么了?如果您认为我的功能不好,请随时向我展示不同的方法(但仍然不使用库),因为我觉得我的功能既复杂又非常慢(当然是错误的...)。

感谢您的宝贵时间。

编辑:根据要求添加新示例。

sentence = "markeatsbread"
a_list = ["bread","daerb","eats","kram","mark","stae"] #these are all the possibles anagrams

正确的结果是:

result = ["stae","mark","daerb"]

错误的结果应该是:

result = ["mark","eats","bread"]   #this could be a possible anagram, but I need the last possible one
result = None        #can't return None because there's at least one anagram

试试这个,看看它是否适用于您的所有情况:

def findAnagram(sentence, word_list):
    word_list.reverse()
    for f_word in word_list:
        if word_list[-1] == f_word:
            break
        index1 = word_list.index(f_word) + 1
        for s_word in word_list[index1:]:
            if word_list[-1] == s_word: break
            index2 = word_list.index(s_word) + 1
            for t_word in word_list[index2:]:
                if (sorted(list(f_word + s_word + t_word)) == sorted(list(sentence))):
                    return (f_word, s_word, t_word)

希望对您有所帮助