0
def minimum(x):
    mini = x[0]
    for i in x[0:]:
        if i < mini:
            mini = i
        else:
            mini = x[0]
    return (mini)
b = [1,2,3,4,5]
c= [3,6,2,7,9]
print minimum(b)
print minimum(c)

My code works for the first list (b) that I used to test (it returns 1 as the minimum), but for the second list (c) it returns (3) and I can't figure out why. Thanks!

:edit: Just figured it out, removing the "else" portion of the for loop fixed the problem

6
  • 3
    What was your reasoning behind that else? Commented May 18, 2015 at 21:32
  • Initially I had the for loop starting at x[1:] so I wanted to include x[0] as a potential candidate for the minimum. When I changed the for loop to include x[0] from the beginning I didn't remove the "else" Commented May 18, 2015 at 21:35
  • @stormageddon: but you already consider x[0] as a lowest value, because that is what you initialise mini to. Commented May 18, 2015 at 21:35
  • If you're having trouble with the logic of a short program like this one, this is a great tool. pythontutor.com/visualize.html#mode=edit Commented May 18, 2015 at 21:39
  • Also I thought that when you use if you had to attach an else to it to complete it. Thanks for all the feedback! Commented May 18, 2015 at 22:39

1 Answer 1

3

Remove the else clause:

def minimum(x):
    mini = x[0]
    for i in x[0:]:
        if i < mini:
            mini = i
    return mini

You don't want to set the minimum back to the first value every time you find a value larger than the miminum found so far...

Without the else, you remember the lowest value found so far. There is no need to do anything else for values that are not lower.

Sign up to request clarification or add additional context in comments.

4 Comments

Is this the definition of the built in min() function in Python? Where can I find its original definition?
No, it is not. The built-in version is written in C, See the source code of the builtins module.
in C! So this is why usually is much faster than our functions defined using while or for?
Yes, there is no Python interpreter loop overhead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.