我应该在while循环中使用try和accept吗?

时间:2017-03-06 03:23:36

标签: python python-2.7

我应该根据提供的最后一个单词的最后一个字母返回一个单词列表。当提供的最后一个字母的最后一个字母不可用时,如果找不到单词,我将遇到问题。像“e”一样,如果没有以字母“e”开头的单词,它将不会终止该函数并抛出错误。

def game(names):
    words_by_letter = {}
    current_word = names[0]
    phrase = [current_word]
    lookup_letter = current_word[-1]
    for name in names:
        if name[0] in words_by_letter:
            words_by_letter[name[0]].append(name)
        else:
            words_by_letter[name[0]] = [name]

    while lookup_letter in words_by_letter:
        if lookup_letter[0]:
            next_word = words_by_letter[lookup_letter][0]
            phrase.append(next_word)
            del words_by_letter[current_word[0]][0]
            current_word = next_word
            lookup_letter = current_word[-1]
        else:
            break

    return phrase



print game(["bagon", "baltoy", "yamask", "starly", "nosepass", "kalob", "nicky", "booger"])
print game(["apple", "berry", "cherry"]) #should return ['apple']
print game(["noon", "naan", "nun"])

1 个答案:

答案 0 :(得分:0)

您可以在while循环中使用flag。

flag = False

while lookup_letter in words_by_letter:
    if lookup_letter[0]:
        next_word = words_by_letter[lookup_letter][0]
        phrase.append(next_word)
        del words_by_letter[current_word[0]][0]
        current_word = next_word
        lookup_letter = current_word[-1]
        flag=True # Here if found it sets flag to true
    else:
        break
if flag:
    return phrase