Reputation: 107
Could anyone tell me why this isn't working? I got error saying:
ValueError: list.remove(x): x not in list
.
But if I try print max
; it prints 9,
and also if I print min
; it prints 1.
list = [3,1,4,9,5,7]
max = list[0]
min = list[0]
list = list[:]
while len(list)> 2:
for i in list:
if(i > max):
max = i
elif(i < min):
min = i
list.remove(min)
list.remove(max)
print list
I need to remove max and min element from list, until there are only 2 elements in order to get the median of the list.
Upvotes: 0
Views: 109
Reputation: 76715
Your problem is that you only initialize the min and max variables once, outside the while
loop.
Your code will work if you initialize inside the loop.
This code works. Note that I changed the variable names to not be Python built-ins. You shouldn't use names that "shadow" built-ins; for example, list
is a built-in type, so you shouldn't use list
as a variable name.
lst = [3,1,4,9,5,7]
lst = lst[:]
while len(lst)> 2:
max_val = lst[0]
min_val = lst[0]
for i in lst:
if(i > max_val):
max_val = i
elif(i < min_val):
min_val = i
lst.remove(min_val)
lst.remove(max_val)
print lst
Note that your code is tremendously inefficient and slow. You could speed it up a bit by using the built-in functions max()
and min()
but the algorithm is still inefficient.
The best thing is to just sort the list, and then pick the single value from the middle of the list (for an odd-length list) or average the middle two values (for an even-length list). Or simply use one of the built-in functions that Python provides.
Upvotes: 1
Reputation: 57520
After list.remove(min); list.remove(max)
is first run, your program goes through the while
loop again, but min
and max
will keep the same values they had on the first pass through the loop, and as nothing remaining in list
is greater than max
or less than min
, the variables won't be changed, and so Python will end up trying to run list.remove(min); list.remove(max)
with the same values for min
and max
that were used before. Since those values were already removed from list
, you get an error.
The simplest solution is to set min
and max
at the start of the while
loop rather than before it:
list = [3,1,4,9,5,7]
list = list[:]
while len(list)> 2:
max = list[0]
min = list[0]
for i in list:
if(i > max):
max = i
elif(i < min):
min = i
list.remove(min)
list.remove(max)
print list
Also note that list
, min
, and max
are already the names of builtin Python functions, and using those names for regular variables is widely considered bad practice. You should rename them to something else (say, lst
, minimum
, and maximum
).
Upvotes: 0