Home > Enterprise >  Function return first index meets condition
Function return first index meets condition

Time:12-30

My function doesn't stop when the first time the condition is met (the lowest value in list started when started at start_index). What do I have to add to achieve it. My code is:

def index_min(l, start_index):
    min_ele = l[start_index]
    idx = []
    for i in range(start_index, len(l)):
        if l[i] <= min_ele:
            min_ele = l[i]
            idx = i
    return idx

print(index_of_min([10, 7, 19, 16, 5, 10, 5, 1, 5, 4, 6, 2, 3, 7, 12, 8, 9, 18, 1, 10, 7, 18],6))

It returns index 18 instead of index 7 start index is 6.

CodePudding user response:

I'm assuming you meant to call index_min() in the print() statement.

If you're looking to get the first appearance of the smallest number, you can change the <= to a <:

def index_min(l, start_index):
    min_ele = l[start_index]
    idx = []
    for i in range(start_index, len(l)):
        # If we see a value equal to the minimum seen so far, don't update the index.
        if l[i] < min_ele:
            min_ele = l[i]
            idx = i
    return idx

print(index_min([10, 7, 19, 16, 5, 10, 5, 1, 5, 4, 6, 2, 3, 7, 12, 8, 9, 18, 1, 10, 7, 18],6))
  • Related