# 15.Median - help me

#1

This is my code -

``````def median(intlist):
if len(intlist) == 1:
return intlist[0]
elif len(intlist) % 2 == 0:
intlist = intlist.sort()
a = intlist[(len(intlist) / 2) - 1]
b = intlist[a + 1]
return (a + b) / 2
else:
intlist = intlist.sort()
return intlist[((len(intlist) + 1) / 2) - 1]``````

The error is -
Oops, try again. median([4, 5, 5, 4]) resulted in an error: object of type 'NoneType' has no len()

I cannot see what is wrong

#2

``intlist = intlist.sort()``

`.sort()` will return a sorted list, no need to also store it in a variable

#3

``````def median(intlist):
if len(intlist) == 1:
return intlist[0]
elif len(intlist) % 2 == 0:
intlist.sort()
a = intlist[(len(intlist) / 2) - 1]
b = intlist[a + 1]
return (a + b) / 2
else:
intlist = intlist.sort()
return intlist[((len(intlist) + 1) / 2) - 1]``````

Now it gives this error -

Oops, try again. median([4, 5, 5, 4]) resulted in an error: list index out of range

#4

I helped you with the issue you have been struggling with for a while, have you any idea what causes this new issue?

`a` doesn't contain an index, so you can't use it to get the value for `b`

#5

I fixed that but it still gives an error that the list index is out of range

#6

Can i see an updated version of your code? I can't guess how you fixed it

#7

``````def median(intlist):
if len(intlist) == 1:
return intlist[0]
elif len(intlist) % 2 == 0:
intlist.sort()
a = intlist[(len(intlist) / 2) - 1]
b = intlist[intlist[intlist.index(a)] + 1]
return (a + b) / 2
else:
intlist = intlist.sort()
return intlist[((len(intlist) + 1) / 2)-1]``````

#8

this line:

``b = intlist[intlist[intlist.index(a)] + 1]``

does the following:

``intlist.index(a)``

getting the index of a, which is 0 (this is the wrong index?)

next step:

``intlist[0]``

getting the value at index 0, at index zero we have a value of 4.

next:

``4 + 1``

increase the value by one. So now our value is 5.

next:

``intlist[5]``

we use 5 as index, but 5 is a value, not an index.

Recommendation: think the logic through, if we have 4 items, the middle two items are at which indexes? What is the easiest way to calculate this indexes so we can get the values?

#9

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