I have a list with 2 minimum numbers and I am trying to get the index of the minimum number 33 at index [5], but my loop stops at [0] once it's found the min. Unsure how to get the get last index value.
rain_data = [33, 57, 60, 55, 53, 33]
min_value = rain_data[0]
min_index = 0
def minimum(rain_data)
for val in range(len(rain_data)):
if rain_data[val] < min_value:
min_value = rain_data[val]
min_index = val
# display the min value and index
print(min_value)
print(min_index)
results = (float(min_value) , min_index)
I have ran the loop and it stops at [0] and not the desired [5] index
CodePudding user response:
Try using <= min_value, then your answer will be 5. Or make your min_index of type array, so you can store all the indexes in the array, so you will get a list of all the indexes where the minimum is found.
CodePudding user response:
rain_data = [33, 57, 60, 55, 53, 33]
minimum = min(rain_data)
out = [i for i,x in enumerate(rain_data) if x == minimum]
print(out[-1])
or
rain_data = [33, 57, 60, 55, 53, 33]
min_index = (len(rain_data) - 1) - rain_data[::-1].index(min(rain_data))
print(min_index)
5
CodePudding user response:
As noted in comment the question can be interpreted in different ways.
position of the LAST minimum
rain_data = [33, 57, 60, 55, 53, 33]
min_value = rain_data[0]
last_min_pos = 0
for i, x in enumerate(rain_data):
if x <= min_value:
min_value = x
last_min_pos = i
Output: 5
position of the NTH minimum (here second)
I would use a dictionary/list to keep track of the positions of each item and a loop to compute the min value.
This logic requires to read the list only once.
With a dictionary:
rain_data = [33, 57, 60, 55, 53, 33]
d = {}
min_val = rain_data[0]
for i, x in enumerate(rain_data):
if x < min_val:
min_val = x
d.setdefault(x, []).append(i)
if len(d[min_val])>1:
print(d[min_val][1])
Output: 5
Same logic with a list:
l = []
min_val = rain_data[0]
for i, x in enumerate(rain_data):
if x < min_val:
min_val = x
l = []
if x == min_val:
l.append(i)
if len(l)>1:
print(l[1])