python - list.remove(x): x not in list, when trying to find median -
python - list.remove(x): x not in list, when trying to find median -
could tell me why isn't working? got error saying: valueerror: list.remove(x): x not in list.
but if seek print max; prints 9, , if print min; prints 1.
list = [3,1,4,9,5,7] max = list[0] min = list[0] list = list[:] while len(list)> 2: in list: if(i > max): max = elif(i < min): min = list.remove(min) list.remove(max) print list i need remove max , min element list, until there 2 elements in order median of list.
your problem initialize min , max variables once, outside while loop.
your code work if initialize within loop.
this code works. note changed variable names not python built-ins. shouldn't utilize names "shadow" built-ins; example, list built-in type, shouldn't utilize list variable name.
lst = [3,1,4,9,5,7] lst = lst[:] while len(lst)> 2: max_val = lst[0] min_val = lst[0] in lst: if(i > max_val): max_val = elif(i < min_val): min_val = lst.remove(min_val) lst.remove(max_val) print lst note code tremendously inefficient , slow. speed bit using built-in functions max() , min() algorithm still inefficient.
the best thing sort list, , pick single value middle of list (for odd-length list) or average middle 2 values (for even-length list). or utilize 1 of built-in functions python provides.
how find median
python list median
Comments
Post a Comment