My professor wrote this median function, and I do not understand it very well. Can someone explain the part i = len(list)/2 and median = avg() and the else ?
def avg_list(numbers): sum = 0 for num in numbers: sum += num avg = float(sum)/len(numbers) print avg def median(list): list.sort() if len(list)%2 == 0:
To add from the example I saw for an even list length:
def median(s): i = len(s) if not i%2: return (s[(i/2)-1]+s[i/2])/2.0 return s[i/2]
This works very well, but I don’t understand the last return s[i/2] ?
For the length of the odd list:
x = [1,2,5,2,3,763,234,23,1,234,21,3,2134,23,54] median = sorted(x)[len(x)/2]
Since x is an odd-numbered list, is [len(x)/2] a floating-point index? I do not get it completely? Any explanation better than mine is greatly appreciated.
python median
GG Sep 28 '11 at 5:23 2011-09-28 05:23
source share