简体   繁体   中英

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.

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.

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

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