Skip to content
Related Articles

Related Articles

Python | Find k longest words in given list

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 25 Apr, 2019

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.




# 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))

Output:

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

 
Method #2 : Using sorted()




# 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))

Output:

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

 
Method #3 : Using heap




# 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))

Output:

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!