The built-in function
max
is one of the most misunderstood functions in Python. That’s because everyone who tries to explain it uses the same stupid example.
What example am I talking about?
Taking a list of numbers and finding the largest number in the list.
Taking a list of numbers and finding the largest number in the list.
That’s just about the most useless example I can think of. Nobody is going to give you a list of numbers and say “find the biggest one”. That just doesn’t happen in real life.
Here’s the problem: nobody tells you how you’re really supposed to use the max function.
It’s a searching function
Searching and sorting are two of the most fundamental algorithms in programming, so it makes sense that Python would give you an easy way to search for things. The way you search with max function is by specifying a key function through the “key=key_function” parameter.
The key function
The key function returns something interesting about an object. This is usually one of the object’s attributes or it’s something that can be easily calculated from the object.
The key function gets called for every object in the list. Once the max function has generated a key value for each object, it searches for the object that maximizes that key value.
For example
- if the key value is a weight, max finds the heaviest object
- if the key value is an age, max finds the oldest object
- if the key value is a distance, max finds the object that’s farthest away
- if the key value is a length, max finds the longest object
- if the key value is a price, max finds the most expensive object
In database terms, it would look something like this
SELECT object
FROM list_of_objects
WHERE object.whatever = MAX(object.whatever)
FROM list_of_objects
WHERE object.whatever = MAX(object.whatever)
So your challenge is to come up with good key functions. Here are some examples to help you get started.
def key_longest_sequence(x):
‘’’ Let’s you search for the longest string, list, or tuple ‘’’
return len(x)
def key_most_words(text):
‘’’ Let’s you search for the string containing the most words ‘’’
return len( text.split() )
def key_most_important(x):
‘’’ Let’s you search for the highest priority object ‘’’
return x.priority
Your own creativity is the only limit!
No comments:
Post a Comment