I thought I’d take the max save on a variable and then locate it on the list and delete it by saving a new list without the greatest value. Then repeat the max function and find the highest value again.
It would work - but in addition to being quite inefficient, you’ll be just scamming what is probably an exercise.
If this is a programming exercise, the idea is precisely to understand the mechanisms necessary for an element search, with comparisons and internal state (higher values found up to the value being analyzed) - and the idea of the author of the exercise to ask the "second highest value" is precisely to force the development of the algorithm by invalidating the use of the "max" function".
Now, in a "real world" function, without being an exercise, if it were a small list of values compared to the available processing time, in addition to the form you proposed, the most usual would be to sort the list of values, with the use of "Sorted", and take the second item.
I recommend you do the exercise - and I’ll give you some tips without giving the whole code:
- 1) organize into a function that receives a list and returns the second highest value. It always gets much easier, than using loose variables inside the module
- you will need a variable to "remember" the highest value found so far, and a second variable to "remember" only the second highest value.
- make a
for
taking each element of your input sequence, and use if
within it to determine whether that is the highest value found so far. If yes, transfer the highest previous value to the other variable, and take that element as the highest value.
That should be enough.
Bonus points: after solving, try to make a function that receives the input sequence, and which of the larger values, in descending order, must be returned - change the function code to be able to return this generic value, instead of always the second largest.