# Median

#1

hi guys, i've just completed this part.
but i've some doubts if my code is "redundant"...

``````def median(x):
blank = []
for i in x:
blank.append(i)
sort = sorted(blank)
print sort
if len(sort) % 2 == 0:
m = len(sort)/2
n = (m - 1)
q = float(sort[m])
print "max apix",q
w = float(sort[n])
print "min apix",w
z = float((q+w)/2)
print "median",z
else:
m = len(sort)/2
q = float(sort[m])
z = float(q)
print "median",z
return abs(z)

print median([1,2,3,4,3,2,1])
print median([4,5,5,4])
print median([6,8,12,2,23])``````

sorry, for too much "prints".
i just need those for understand if i make some mistake...
Have a nice day all!

Problem with median
#2

1. the first for loop is basically putting the list x into blank. For is unnecessary here. What you did was essentially place the items in x into blank one at a time and sort the list blank every time a new

2. you honestly don't need so many variables

3. I'd go with return in side a function, since 1) codecademy seems to prefer it this way and 2) it gives more flexibility about our use of the result

4. I didn't convert the number into float...out of person preference lol. but using dividing the number by a float (/2.0) will be able to give you a float result

5. converting the median to float is redundant for lists with odd number of items

``````def median(x):
sort = sorted(x)
if len(sort) % 2 == 0:
return (sort[len(sort)/2] + sort[len(sort)/2-1])/2.0
else:
return sort[len(sort)/2]

print median([1,2,3,4,3,2,1])
print median([4,5,5,4])
print median([6,8,12,2,23])``````

Let me know if anything sounds odd to you

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.