Exploring More Uses of min() and max()
00:00
More Uses of min()
and max()
. Let’s say you have a dictionary with the names and prices of several products, and you want to identify the cheapest and most expensive. In this situation, you can use the .items()
and an appropriate lambda
function as the key
argument. In
00:33
this example, the lambda
function takes a key-value pair as an argument and returns the corresponding value so that min()
and max()
have proper comparison criteria.
00:43
As a result, you get a tuple with the cheapest and most expensive products in the input data. Another interesting example of using min()
to solve a real-world problem is when you need to figure out if two numbers are coprime. In other words, you need to know if your numbers’ only common divisor is one.
01:03 In this situation, you can use a Boolean-valued or predicate function as seen on-screen.
01:19
Here, you define are_coprime()
as a predicate function that returns True
if the input numbers are coprime. If they’re not, the function returns False
.
01:30
The function’s main component is a for
loop that iterates over a range of values. To set the upper limit for this range
object, you use min()
with the input numbers as arguments. Again, you’re using min()
to set the upper limit of an interval. You
01:50
can also use min()
to compare several algorithms and evaluate their execution times to determine which algorithm is the most efficient. The example you’ll see uses timeit.repeat()
to measure the execution times for two different ways of building a list containing the square values of the numbers from 0
to 99
. The
02:28
call to timeit.repeat()
runs a string-based statement a given number of times. In these examples, the statement is repeated three times. The call to min()
returns the smallest execution time from the three repetitions.
02:42
By combining min()
, repeat()
, and other Python timer functions, you can get an idea of which of your algorithms is most efficient in terms of execution time.
02:51
The example just seen shows that list comprehensions can be a little bit faster than the built-in map()
function when it comes to building new lists.
03:02
In the next section of the course, you’ll take a look under the hood of min()
and max()
.
Become a Member to join the conversation.