lundi 29 avril 2019

Is there an easy way to get longest word that contains a certain letter?

I am trying to get the largest word that contains the letter 'f' through a for loop, through my code I tried to make it as simple as possible with a if and and statement. It is however not working as it returns the largest word but not the one that includes the letter f, why is it not working?

def main():
    sentence = "Absence makes the heart grow fonder"
    letter = "f"
    longest_word = get_longest_word(sentence, letter)
    print('"' + longest_word + '" is the longest word containing the letter "'
          + letter + '".')

def get_longest_word(sentence, letter):
    words_list = sentence.split()
    largest = words_list[0]
    my_list = []
    for word in words_list:
        if letter in word and len(word) > len(largest):
            largest = word
    return largest 


main()

Aucun commentaire:

Enregistrer un commentaire