简体   繁体   中英

Python - Finds the index of the smallest element in the list A from index k onwards

I am stuck in finding how I can take the "k" in consideration to solve the following problem. Basically, it should start at index k and look for the lowest value in the range from k until the end of the list.

def find_min_index(A, k):
    """
    Finds the index of the smallest element in the list A from index k onwards

    Parameters:
        A (list)
        k: index from which start search

    Example use:
    >>> find_min_index([1, 2, 5, -1], 0)
    3
    >>> find_min_index([1, 1, 1, 5, 9], 2)
    2
    """

    minpos = A.index(min(A))
    return minpos

One-liner solution is this:

return A[k:].index(min(A[k:]) + k

You select the minimal element from A[k:], find its index in A[k:] and add k to it to compensate the search area.

A slightly neater solution is this:

slice = A[k:]
return slice.index(min(slice)) + k

You can add k to the index calculated from a sliced input list:

def find_min_index(A, k):
    sliced = A[k:]
    return k + sliced.index(min(sliced))

find_min_index([1, 2, 5, -1], 2)    # 3
find_min_index([1, 1, 1, 5, 9], 2)  # 2

You could use enumerate to find the index of min:

def find_min_index(A, k):
    """
    Finds the index of the smallest element in the list A from index k onwards

    Parameters:
        A (list)
        k: index from which start search

    Example use:
    >>> find_min_index([1, 2, 5, -1], 0)
    3
    >>> find_min_index([1, 1, 1, 5, 9], 2)
    2
    """

    o, _ = min(enumerate(A[k:]), key=lambda i: i[1])
    minpos = k + o
    return minpos


print(find_min_index([1, 2, 3, 4], 1))
print(find_min_index([4, 3, 2, 1], 1))

Output

1
3

You can use enumerate to keep track of the original index before you slice the list with k as the starting index:

from operator import itemgetter
def find_min_index(A, k):
    return min(list(enumerate(A))[k:], key=itemgetter(1))[0]

so that:

print(find_min_index([1, 2, 5, -1], 0))
print(find_min_index([1, 1, 1, 5, 9], 2))

would output:

3
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM