Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function return first index meets condition

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading