Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
15.7. Finding the Largest or Smallest Value¶
Another common pattern for working with lists is finding the largest or smallest value. We saw an example of code to do this earlier, but let’s break down the important parts of this recipe.
We need to have a “tracking variable” that will store the largest (or smallest value we have seen). The easiest way to initialize that variable is to use the first value from the list (index 0). When we are starting, the first value is the largest (or smallest) we have seen.
We then loop through the values and compare each to the highest value. If the current value is higher than the largest we have seen (or smaller than the lowest), we change our tracking variable to hold that new “best” value.
This program is designed to find the highest value. It works correctly - you can run watch it run in code lab to see step by step how it does its job.
Modify it to find the lowest value:
Change the tracking variable’s name to
Change the comparison used in the if. If the current score is lower then the
lowest, we have found a new lowest value.
If we are not sure that the list has any items, we can’t start with the first item. In that case we can start with some value that is so low (or high as appropriate) we are confident the first item we do look at will be “better” and replace the starting one.
The program above could use 0 as the initial value for
highest - the first value we see would
be sure to be higher. But once we change the program to look for the lowest, we would have to
change the starting value to 101 or something large to guarantee that any real values we looked at
would be lower.
This is trickier to get right than just starting with the first value, so we won’t need it unless we have to.
Sometimes the max or min pattern might need to be modified to work with values calculated from each item. Here is an example of adapting the basic recipe to find the longest name in a list of names: