Exploring More Uses of min() and max()
More Uses of
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
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.
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
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
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.
Become a Member to join the conversation.