-1
\$\begingroup\$
def minval(xs):
    minum = xs[0]
    for i in range(len(xs)):
        if xs[i] < minum: #difference in code: xs[i]
            minum = xs[i]
    return minum

or

def minval(xs):
    minum = xs[0]
    for i in range(len(xs)):
        if i < minum: #difference in code: i
            minum = xs[i]
    return minum

It gives me the same results:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print minval(lst)

1

Which one is better? Why do they both give the same result?

Is there a better more shorter way to get the same result, without resorting to pythons own functions?

Edit: I got it why it works, I ran the second one, it looped through the "i" which was just the numbers from the range of the len of xs and not the actual indexes of xs.

\$\endgroup\$
  • 4
    \$\begingroup\$ What's wrong with Python's built-in function min? \$\endgroup\$ – Gareth Rees Nov 10 '13 at 12:38
4
\$\begingroup\$

They aren't the same: The second gives -1 for [-1,-2,-3] and is simply spuriously correct, while the first gives the correct answer.

\$\endgroup\$
2
\$\begingroup\$

A slight improvement would be:

def minval(xs):
    minimum = xs[0]
    for x in xs[1:]:
        if x < minimum:
            minimum = x
    return minimum

In general you should loop through the values in a list rather than finding the range and then looping through the indices. If you really need the indices you can also use enumerate.

But as others have said, you would simply use min for this.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy