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

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
stormageddon
  • 3
  • 1
  • 1
  • 4
  • 3
    What was your reasoning behind that `else`? – user2357112 May 18 '15 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" – stormageddon May 18 '15 at 21:35
  • @stormageddon: but you *already* consider `x[0]` as a lowest value, because that is what you initialise `mini` to. – Martijn Pieters May 18 '15 at 21:35
  • If you're having trouble with the logic of a short program like this one, this is a great tool. http://www.pythontutor.com/visualize.html#mode=edit – DJMcMayhem May 18 '15 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! – stormageddon May 18 '15 at 22:39
  • Does this answer your question? [Min and Max of a List (without using min/max function)](https://stackoverflow.com/questions/15148491/min-and-max-of-a-list-without-using-min-max-function) – Tomerikoo Nov 21 '22 at 15:11

1 Answers1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Is this the definition of the built in `min()` function in Python? Where can I find its original definition? – Sigur Feb 20 '18 at 18:30
  • 1
    No, it is not. The built-in version is written in C, See the [source code of the builtins module](https://github.com/python/cpython/blob/v3.6.4/Python/bltinmodule.c#L1520-L1652). – Martijn Pieters Feb 20 '18 at 18:34
  • in C! So this is why usually is much faster than our functions defined using `while` or `for`? – Sigur Feb 20 '18 at 18:40
  • Yes, there is no Python interpreter loop overhead. – Martijn Pieters Feb 20 '18 at 18:45