Could anyone please explain to me why this is not working? The error message I'm getting is: TypeError: list indices must be integers or slices, not float.
def median(lst):
s = sorted(lst)
l = len(lst)/2
if len(lst) % 2 == 0:
print((s[l] + s[l-1])/2.0)
else:
print(s[l])
median([3,3,5,6,7,8,1])
error you made is in calculating l
dividing using operator /
returns actual division i.e. a floating point value while //
returns only quotient i.e. an integer
hence
you should calculate l
as follows
l = len(lst) // 2
or convert l
to int
using
l = int(l)