vendredi 4 juin 2021

for loop exit if condition is not met

I am trying to write a Shiritori game in Python. In the game you are given a word (ex: dog) and you must to add another word that starts with the end of the previous word ex(: doG, Goose). So given a list words = ['dog', 'goose', "elephant" 'tiger', 'rhino', 'orc', 'cat'] it must return all value, but if "elephant" is missing it must return: ["dog","goose"] because "dog" and "goose" match, but "goose" and "tiger" not.

I am running into a bug where it either loop out of range checking next index in list or it returns only "dog" and not "goose", or it returns ["dog","goose"] and than exit the loop without iterating through the rest of the list(s). What am I doing wrong?

def(game():
words = ['dog', 'goose', 'tiger', 'rhino', 'orc', 'cat']
check_words = ['goose', 'tiger', 'rhino', 'orc', 'cat']
# check words has one less element to avoid index out or range in the for loop
# example = if word[-1] != words[index+1][0]: # index+1 gives error
good_words = []
for index, word in enumerate(words):
    for index2, word2 in enumerate(check_words):
        # I want to add the correct pair and keep looping if True
        if word[-1] == word2[0]:
            good_words.extend([word,word2])
    return good_words # break out of the loop ONLY when this condition is not met
print(game())

Aucun commentaire:

Enregistrer un commentaire