Python | Find k longest words in given list

Given a list of words and a positive integer K, write a Python program to find k longest words in the list in descending order of length.

Examples:

Input : lst  = ['am', 'watermelon', 'girl', 'boy', 'colour'], K = 3
Output : ['watermelon', 'colour', 'girl']

Input : ['see', 'I', 'geek', 'on', 'brain'], K = 4
Output : ['brain', 'geek', 'see', 'on']

 
Method #1 : Using count() from itertools



First, sort the ‘lst’ based on length of the words and then based on a counter variable, so that words occurring later gets higher priority and thus, extract k variables.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Find 
# longest K words in a list
from itertools import count
  
def longest_word(lst, K):
    cnt = count()
    return sorted(lst, key = lambda w : (len(w), next(cnt)), 
                                        reverse = True)[:K]
  
# Driver code
lst = ['am', 'watermelon', 'girl', 'boy', 'colour']
K = 3
print(longest_word(lst, K))

chevron_right


Output:

['watermelon', 'colour', 'girl']

 
Method #2 : Using sorted()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Find 
# longest K words in a list
  
def longest_word(lst, K):
    idx, words = zip(*sorted(enumerate(lst), 
    key = lambda w: (-len(w[1]), -w[0]))[:K])
    return list(words)
  
# Driver code
lst = ['am', 'watermelon', 'girl', 'boy', 'colour']
K = 3
print(longest_word(lst, K))

chevron_right


Output:

['watermelon', 'colour', 'girl']

 
Method #3 : Using heap

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Find 
# longest K words in a list
import heapq
from operator import itemgetter
  
def longest_word(lst, K):
    # constructing heap
    heap = [(0, i, '') for i in range(K)]
    heapq.heapify(heap)
  
    # To maintain top K elements
    for i, word in enumerate(lst):
        item = (len(word), i, word)
        if item > heap[0]:
            heapq.heapreplace(heap, item)
  
    return sorted(list(map(itemgetter(2), heap)),
                            key = len, reverse = True)
  
  
# Driver code
lst = ['am', 'watermelon', 'girl', 'boy', 'colour']
K = 3
print(longest_word(lst, K))

chevron_right


Output:

['watermelon', 'colour', 'girl']


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.