Strings, Lists
We can do this by keeping track of the best seen so far:
def find_longest_word(words):
"""Return longest word in list of words."""
# START SOLUTION
longest = len(words[0])
for word in words:
if longest < len(word):
longest = len(word)
return longest
Another way: we could use a list comprehension to make a new list of words-lengths, and return the largest number in that list:
def find_longest_word_max(words):
"""Return longest word in list of words.
For example::
>>> find_longest_word_max(["hi", "hello"])
5
>>> find_longest_word_max(["Balloonicorn", "Hackbright"])
12
"""
return max([len(w) for w in words])
Python’s max function finds the biggest thing in a list (or set or tuple) — but it also take a second argument, a “key” function which it can use to determine how to judge which is the biggest.
For example, for the numbers [-5, 1, 2]
, the largest is 2. If we consider only
the absolute values, though, we could find use this “key function” capability to have it
consider the absolute values of the numbers:
>>> max([-5, 1, 2], key=abs)
5
(abs is the built-in function for Python to return the absolute value of a passed-in number)
We can use this for our longest word, too:
def find_longest_word_clever(words):
"""Return longest word in list of words.
For example::
>>> find_longest_word_clever(["hi", "hello"])
5
>>> find_longest_word_clever(["Balloonicorn", "Hackbright"])
12
"""
return len(max(words, key=len))
Here, we’re saying “considering the length of words, find the longest word, then return the length of it.”
Key functions are really useful; you’ll can use them with Python’s min, max, sorted, and a few other places.