Reputation: 661
I want to find the minimum value in a list. I know I can use min()
, but I am learning Python and want to implement this for practice on my own:
x=[2,3,5,9,1,0,2,3]
z=len(x)-1
i=0
for i in range(z):
if x[i]<x[i+1]:
y=x[i]
else:
y=x[i+1]
print(y)
This doesn't find the minimum though. How can I change this to find the minimum of the list x
?
Upvotes: 2
Views: 35469
Reputation: 43487
Try to stop indexing lists with integers. It is far easier to just iterate through the list.
x = [2,3,5,9,1,0,2,3]
def my_min(sequence):
"""return the minimum element of sequence"""
low = sequence[0] # need to start with some value
for i in sequence:
if i < low:
low = i
return low
print my_min(x)
Upvotes: 4
Reputation: 21
You're checking adjacent values and comparing them to see which one's bigger and assigning that to y. If you want to find the minimum value in your list it has to be the universal minimum as in smallest of all values. So instead of checking for the smallest element between two adjacent elements, you should check each element of the list with your current minimum value, if you come across an element that is smaller than your minimum, that element becomes your minimum.
Upvotes: 1
Reputation: 517
You are not keeping track of the minimum through your iteration at all. Therefore, what happens in your code in effect is that the minimum of the last two values (2 and 3, in this case) is returned.
To correct this, maintain a minimum seen so far, and update it if the value in the iteration is less than that. Then, at the end of your iteration, it will hold the minimum of the list.
Upvotes: 1
Reputation: 2530
add a temp (temporary variable) , this is where you will store the minimum value for x[0] and x[1]
then x[1] and x[3]
so forth. cheers
Upvotes: 0
Reputation: 3524
Your problem is that you are only comparing values that are right next to each other in the list. Your program should instead remember the smallest value you've checked so far and compare the others against that.
That's your hint!
Upvotes: 4