Write longest_words(words: list[str], k: int) -> list[str] that returns the k longest words of words, using heapq.nlargest.
- The longest word comes first.
- Words of the same length keep the order they have in
words. - A word that appears several times counts each time. If
kis at leastlen(words), return every word in that order;k == 0gives[].
longest_words(["fig", "banana", "kiwi", "cherry", "plum", "apple"], 3)
# ["banana", "cherry", "apple"]
longest_words(["ab", "cd", "e"], 5)
# ["ab", "cd", "e"]
0 <= len(words) <= 10^5,0 <= k <= 10^5, and words are 1 to 30 lower-case letters.- Don't modify
words.
Show hint
heapq.nlargest(k, iterable, key=...) takes the same key argument as sorted, and its result is the same as sorted(iterable, key=..., reverse=True)[:k], ties included.