Search code examples
pythonmedian

Median code explanation


My professor wrote this median function and I don't understand it very well. Can someone please explain the part about i = len(list)/2 and median = avg() and the else statement?

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:
        #have to take avg of middle two
        i = len(list)/2
        median = avg()
    else:
        #find the middle (remembering that lists start at 0)
        i = len(list)/2
        median = list        
    return median

To add from an example I saw, for 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 odd list length:

x = [1,2,5,2,3,763,234,23,1,234,21,3,2134,23,54]
median = sorted(x)[len(x)/2]

Since x has a list length of odd, wouldn't the [len(x)/2] be a floating number index? I'm not getting this all the way? Any explanation better than mine is much appreciated.


Solution

  • We're missing some code here, but we can puzzle it out.

    The comments here are instructive. When we check:

        if len(list)%2 == 0:
    

    Then we're checking to see if the list is of even length. If a list has an even number of members, then there is no true "middle" element, and so:

        #have to take avg of middle two
            i = len(list)/2
            median = avg()
    

    We assume that the avg() function is going to return the average of the two middle elements. Since you didn't include a definition of an avg function, it's possible that this is really supposed to be an avg_list function taking the middle two elements of the list.

    Now, if the list is of odd length, there is a middle element, and so:

        else:
            #find the middle (remembering that lists start at 0)
            i = len(list)/2
            median = list
    

    Now this looks kinda wrong to me too, but my guess is that the intention is that this should read:

    median = list[i]
    

    That would be us returning the middle element of the list. Since the list has been sorted, that middle element is the true median of the list.

    Hope this helps!