15.median


#1



Oops, try again. median([1]) resulted in an error: list indices must be integers, not float

I m assuming every odd number/2 will have .5 left behind , and it would make sense that I add .5 to round it up. is it?


def median(lst):
    resutlt=0
    while lst>0:
        sorted(lst)
        if len(lst)%2==0:
            result=(lst[len(lst)/2-1]+lst[len(lst)/2+1])/2
        else:
            result=lst[len(lst)/2.0+.5]
    return result


#2

In Python 2, which we're using, integer division gives an integer result.

7 / 2 == 3

But given that lists are zero-indexed, 3 is the middle index, hence the median.

Now consider an even length:

8 / 2 == 4

With zero-indexing, this is the higher of the two middle indices

[4 - 1]  &  [4]

would be the middle pair.

Now on this median, the sum of the two values may be odd, so dividing by 2 will give an integer result, which we don't want. Implicit casting to float with 2.0 is okay, and probably shown in one lesson or another, so I won't vehemently object, just toss out my old, 'counting numbers are not floats' speech. The explicit approach to me makes for more readable code.

float( sample[m - 1] + sample[m] ) / 2

#4

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