how to find the longest N words from a list, using python?

2024/7/7 9:57:35

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:

  1. The print order does not matter
  2. 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)
  3. assume that each row in the file contains only one single word
  4. 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 = wordprint(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!

Answer

One alternative is to use a heap to maintain the top-n elements:

import heapq
from operator import itemgetterdef top(lst, n=4):heap = [(0, i, '') for i in range(n)]heapq.heapify(heap)for i, word in enumerate(lst):item = (len(word), i, word)if item > heap[0]:heapq.heapreplace(heap, item)return list(map(itemgetter(2), heap))words = ['Mother', 'Dad', 'Cat', 'Bicycle', 'House', 'Hat']print(top(words))

Output

['Hat', 'House', 'Bicycle', 'Mother']

In the heap we keep items that correspond to length and position, so in case of ties the last one to appear gets selected.

https://en.xdnf.cn/q/119564.html

Related Q&A

([False, True] and [True, True]) evaluates to [True, True]

I have observed the following behavior in python 3: >>> ([False, True] and [True, True]) [True, True]>>> ([False, True] or [True, True]) [False, True]I was expecting exactly the oppos…

Uploading an image to Flask server

I am struggling bit with Flask and uploading a file, here is my Flask code so far:@app.route(/api/user/update/, methods=[PUT]) @auth.login_required def update_user():# check if the post request has the…

Enemy Projectiles Arent Appending On Screen

I have here my script that targets the player what ever position he is at but the projectiles arent showing on my screen VIDEO. He isnt attacking at all, I dont know why. I am in my main loop I draw t…

Python+Selenium. Cant locate element

Ive implemented the script using Python and selenium to click on the ads. But now this script is not working.Unable to find element on the page.Please help me to correct the script. Thank you!from sele…

AttributeError: NoneType object has no attribute channels [duplicate]

This question already has answers here:Why do I get AttributeError: NoneType object has no attribute something?(11 answers)Closed 5 years ago.Hi Im having an issue with a module for my Discord bot. Im…

How to get a specific value from a html header

Im using selenium to get request headers from a web page, the problem is that it prints out all request headers sent and i want to get only one value from one of them. I dont know how to do it and i ha…

How to use windows as raspberry pi and connect the windows with another raspberry pi [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 4…

Python : Return the missing weekdays dates and assign rate next to missing date

Dates rates 7/26/2019 1.04 7/30/2019 1.0116 7/31/2019 1.005 8/1/2019 1.035 8/2/2019 1.01 8/6/2019 0.9886 8/7/2019 1.0048 8/8/2019 0.97 8/9/2019 0.9659 8/12/2019 0.965In …

How do I use a list or set as keys in file renaming

Is something like this possible? Id like to use a dictionary or set as the key for my file renamer. I have a lot of key words that id like to filter out of the file names but the only way iv found to …

How to change Python comment font style in the latest VS Code? [duplicate]

This question already has an answer here:How to change the font-style of code comments in vscode?(1 answer)Closed 6 months ago.Seems like with the latest VS Code update, all the comment font style has…