Emulating Python's min() and max()
max(). While Python provides you with
max() to find the smallest and largest values in your data, learning how to do this computation from scratch is a helpful exercise that can help improve your logical thinking and your programming skills.
00:27 To find the minimum value in a small list of numbers as human, you’d normally check the numbers and implicitly compare all of them in your mind. Yes, your brain is pretty amazing, but computers aren’t that smart.
00:39 They need detailed instructions to accomplish any task. You’ll have to tell your computer to iterate over all the values while comparing them in pairs. In the process, the computer has to take note of the current minimum value in each pair until the list of values is exhausted. This explanation may be hard to visualize, so on-screen there’s a Python function that does the work.
for loop iterates over the rest of the elements in the input data. The conditional statement compares the current
value to the tentative
minimum in the first iteration. If the current
value is smaller than
minimum, then the conditional updates
To write your custom implementations of
max(), you’ll start by coding a helper function that’s able to find the smallest or largest value in the input data, depending on the arguments you use in the call.
The body of
min_max() will start by processing
*args to build a list of values. Having a standardized list of values will allow you to write the required algorithm to find the minimum and maximum values in the input data.
min_max() in place, the final step is to define two independent functions on top of it. These functions will use appropriate comparison operator functions to find the minimum and maximum values, respectively.
Become a Member to join the conversation.