pythonbeginner4556
pythonbeginner4556

Reputation: 313

Creating a function that returns index of minimum value in a list?

def minimum_index(xs):
    minimum_index=xs[0]
    for i in range(len(xs)):
    if xs[i]<xs[i+1]:
        min_i=i
    elif xs[i]>xs[i+1]:
        min_i=i+1
        continue
return minimum_index

This looks correct to me, but for some reason, I keep trying to change things around and I either get an incorrect return value or no return value.

Upvotes: 0

Views: 41

Answers (2)

Shreevardhan
Shreevardhan

Reputation: 12641

Simplify the function

def minimum_index(xs):
    ans = 0
    for i in range(1, len(xs)):
        if xs[i] < xs[ans]:
            ans = i
    return ans

or in a more pythonic way

minimum_index = lambda xs: xs.index(min(xs))

Upvotes: 1

burnpanck
burnpanck

Reputation: 2196

Your code has at least two issues: You seem to have two variables that stand for the minimal index, and you mix them up. Also, it is not enough to compare subsequent elements, you will have to compare to the minimal value. Try this:

def minimum_index(xs): minx = xs[0] mini = 0 for i in range(1,len(xs)): if xs[i]<minx: mini = i minx = xs[i] return mini

If you are using numpy, then you can simply use their numpy.argmin(xs).

Upvotes: 0

Related Questions