I am now studying Python, and I am trying to solve the following exercise:
Assuming there is a list of words in a text file, My goal is to print the longest N words in this list.
Where there are several important points:
- The print order does not matter
- Words that appear later in the file are given priority to be selected (when there are several words with the same length, i added an example for it)
- assume that each row in the file contains only one single word
- Is there a simple and easy solution for a short list of words, as opposed to a more complex solution for a situation where the list contains several thousand words?
I have attached an example of the starting code to a single word with a maximum length,
And an example of output for N = 4, for an explanation of my question.
Thanks for your advice,
word_list1 = open('WORDS.txt', 'r')
def find_longest_word(word_list):
longest_word = ''
for word in word_list:
if len(word) > len(longest_word):
longest_word = word
print(longest_word)
find_longest_word(word_list1)
example(N=4):
WORDS.TXT
---------
Mother
Dad
Cat
Bicycle
House
Hat
The result will be (as i said before, print order dosen't matter):
Hat
House
Bicycle
Mother
thanks in advance!