Practise Makes Perfect: 15:median


Practise Makes Perfect: 15:median

median([4, 5, 5, 4]) returned 4.0 instead of 4.5

Expect to return 4.5!!

def median(list):
    divide_these = []
    if len(list) == 1:  #returns single number lists as median
        return list[0]
    elif len(list) % 2 == 0:  #checks if list length is even:
        divide_these.append(list[len(list) / 2])
        divide_these.append(list[len(list) / 2 + 1])
        return float((divide_these[0] + divide_these[1]) / 2)
    else:     #for odd list lengths
        middle = (len(list) + 1) / 2
        return list[middle]

I've tried to comment a little as it's quite dense code (for me anyway!!)


Think I fixed the issue by:

return (divide_these[0] + divide_these[1]) / 2.0

Now it's taking issue with the else statement, throwing:

"median([6, 8, 12, 2, 23]) returned 2 instead of 8"


This needs an assignment, It is not in-place sort.

s = sorted(list)

In-place sort,


list is a reserved word. Best avoid using it as a variable.

Implicit declaration of float is okay in principle, but in practice it is misleading. A counting number is never a float, but two unknown quantities added could feasibly be a float.

float(m[0] + m[1]) / 2

Explicit declaration is more to the point.


Thanks, I think I was working the whole time with an unordered list, the instructions for sorting the list are very misleading.

The other confusing/misleading thing for anyone else who is stuck is that list length and list index do not match up, as it were. So if len(list) == 4, you want to find indices 1 and 2!!


Because of zero-indexing, all indexes are offset by -1 from the length or their physical position (counting from 1). Length is always 1 greater than the last index.

 s   u   r   p   r   i   s   e
[0] [1] [2] [3] [4] [5] [6] [7]

n = len('surprise')

m = int(n / 2)

Middle pair of letters are at, index[m-1] and index[m].

print 'surprise'[m-1:m+1]    # pr


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