Reputation: 35
I have a list like this:
myList = [10, 7, 11, 5, 8, 9, 6]
I want to find the max element and index AFTER the absolute minimum in the list. I've done it by making a new list with all elements from 5 onwards and then finding the max. But if it's possible, I want to do everything using the original list.
So, how do I find maximum value and index of it that occurs after the absolute minimum?
Upvotes: 2
Views: 1703
Reputation: 40773
Keep in mind that most functions which calls the builtin min
and max
functions will scan the list more than once, but less than twice: the first scan for min will scan the entire list, the second will scan part of the list. Also, beware of solutions which create slides of the list (hint: look for the colon (:
) symbol. Creating slide is alright, unless the size of the list is large then performance will be affected.
My solution will scan the list once, does not create any sub-list:
def minmax(seq):
min_value = max_value = seq[0]
for element in seq:
if element <= min_value:
min_value = max_value = element
elif element > max_value:
max_value = element
return min_value, max_value
print(minmax([10, 7, 11, 5, 8, 9, 6]))
Output:
(5, 9)
element
that is smaller than the current min_value
), we reset both min_value
and max_value
. If we see a new maximum, update it.Upvotes: 0
Reputation: 26335
You can also use enumerate()
for this:
>>> from operator import itemgetter
>>> myList = [10, 7, 11, 5, 8, 9, 6]
>>> min_index = min(enumerate(myList), key = itemgetter(1))[0] # or key = lambda x: x[1]
>>> max(myList[min_index:])
9
Upvotes: 0
Reputation: 28656
O(1) space:
myList = [10, 7, 11, 5, 8, 9, 6]
n = len(myList)
key = myList.__getitem__
imin = min(range(n), key=key)
imax = max(range(imin + 1, n), key=key)
print('maximum', myList[imax], 'is at index', imax)
Prints:
maximum 9 is at index 5
Upvotes: 1
Reputation: 71471
You can try this:
myList = [10, 7, 11, 5, 8, 9, 6]
abs_max = max(myList[myList.index(min(myList)):])
Output:
9
Upvotes: 2
Reputation: 364
If you don't know what the absolute minimum will be in advance, you're going to have to iterate over the entire list, in which case you might as well store your smallest and largest values in separate variables and then use index
to find them if you really don't want to create a new list.
*edit: Sagun's answer is more sophisticated.
Upvotes: 0
Reputation: 1198
You can do like this
myList = [10, 7, 11, 5, 8, 9, 6]
min_index = myList.index(min(myList))
print(max(myList[min_index:]))
Output
9
Upvotes: 2