简体   繁体   English

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

[英]Should I use try and accept in a while loop?

I am supposed to return a list of words based upon the last letter of the last word that is provided. 我应该根据提供的最后一个单词的最后一个字母返回单词列表。 I am having issues terminating when a word is not found when the last letter of the last word provided is not available. 当提供的最后一个单词的最后一个字母不可用时,当找不到单词时,我遇到了终止问题。 Like "e", if there are no words that start with the letter "e", it will not terminate the function and throw and error. 像“ 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"])

You can use flag in while loop. 您可以在while循环中使用标志。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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