Oct-17-2018, 08:03 PM
>>> def n_max(seq, n=2): ... max_items = sorted(enumerate(seq), key=lambda x: x[1])[-1 * n:] ... return max_items[::-1] ... >>> items = [4, 5, 3, 2, 63, 0, 1, 5] >>> n_max(items, 2) [(4, 63), (7, 5)]Here you go, pal. Hopefully this isn't homework, because an instructor wouldn't accept this lol.
So what we do here, is use
enumerate()
to create a list of index-value pairs, which we then sort by value, using the key
argument of sorted()
. Once the list is sorted by value, we simply grab the n
items off the end of the list, since the largest values are at the end, and reverse it before returning it so the largest item is the first in the result set.