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

时间:2019-01-31 22:43:21

标签: python-3.x anagram

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

"johndrinksmilk"

和单词列表,其中仅包含可能是上述句子的字谜的单词,这些单词也按字母顺序排列,例如:

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

我想创建一个函数(不使用库),该函数返回三个单词的元组,它们可以一起构成给定句子的字谜。该元组必须是该句子的最后可能的字谜。如果给定列表中的单词不能用于组成给定句子,则该函数应返回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

但不返回:

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

它返回:

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

1 个答案:

答案 0 :(得分:2)

尝试一下,看看它是否适用于所有情况:

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)

希望这对您有帮助