I am trying to find the longest word in a non-empty list. My function is supposed to return the longest word. If elements are of equal length in the list, I am trying to sort out the longest in terms of Unicode sorting. For example, I am trying to return the following:
>>> highest_word(['a', 'cat', 'sat'])
'sat'
>>> highest_word(['saturation', 'of', 'colour'])
'saturation'
>>> highest_word(['samIam'])
'samIam'
So far I can get the first one to work, this is my code so far:
def highest_word(wordlist):
longestWord = ""
max_len = 0
for word in wordlist:
if len(word) > max_len:
longestWord = len(word)
longestWord = word
return longestWord
Any sort of help would be greatly appreciated.
Here's a simple one liner
print(max(['a', 'cat', 'sat', 'g'], key=lambda s: (len(s), s)))
This works by mapping each element of the list to a tuple containing its length and the string itself.
When comparing two tuples A
and B
, if A[0] > B[0]
then A > B
. Only if A[0] == B[0]
are the second elements considered. So if the lengths of two strings are equal, then the strings are compared as a tiebreaker.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.