2

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.

1 Answer 1

10

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.

3
  • Yeah I've tried this before. It doesn't seem to work for the first one. It returns 'cat' instead of 'sat'. It seems to only work for the lists that have only one long word, such as the second one, which returns 'saturation' fine.
    – RoadRunner
    Mar 25, 2016 at 4:42
  • Thanks guys, I appreciate the help alot. Is their a way to mark two answers as correct?
    – RoadRunner
    Mar 25, 2016 at 4:55
  • 3
    No. But I strongly encourage you to use this solution. James's answer will work, but it takes time proportional to the length of the list squared (O(N^2)). max(map(len, a)) iterates over the whole list, and is computed for each element of the list. BAH's answer takes time proptional to the length of the list (O(N)). Mar 25, 2016 at 4:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.