Noah Dukehart
Noah Dukehart

Reputation: 171

writing a median function

i am trying to write a median function, currently i have one that takes a list and sorts it and then gives the median. but i am trying to rewrite it so that if the list has an even number of elements it doesnt print the median but rather the 2 numbers from the list that the median is between. heres my code

def getMedian(A):
    A=sorted(A)
    n=len(A)
    m=n-1
    return (A[int(n/2)]+A[int(m/2)])/2

def main():
    myList=[3,5,9,3,11]
    print(getMedian(myList))
    myList=[3,9,11,5]
    print(getMedian(myList))
main()

currently it outputs 5 and then 7 but im trying to get it to output 5 and then 5,9 any advice?

Upvotes: 1

Views: 802

Answers (3)

Vlad Bezden
Vlad Bezden

Reputation: 89527

Here is an example of doing it.

def getMedian(A):
    A.sort()
    mid = len(A) // 2
    return [[A[~mid], A[mid]], (A[mid] + A[~mid]) / 2][len(A) % 2]


def main():
    myList = [3, 5, 9, 3, 11]
    print(getMedian(myList))
    myList = [3, 9, 11, 5]
    print(getMedian(myList))


main()

output

5.0
[5, 9]

Upvotes: 0

Alexander Safronov
Alexander Safronov

Reputation: 76

import statistics

statistics.median(data)

Upvotes: 1

adrianus
adrianus

Reputation: 3199

You could check if the list has an odd number of elements and then change the return value(s) accordingly:

def getMedian(A):
    A = sorted(A)
    n = len(A)
    m = n-1
    if n%2 == 1:
        return (A[int(n/2)]+A[int(m/2)])/2
    else:
        return A[int(m/2)], A[int(n/2)]

def main():
    myList = [3,5,9,3,11]
    print(getMedian(myList))
    myList = [3,9,11,5]
    print(getMedian(myList))

main()

Output:

>>> 
5
(5, 9)

Upvotes: 0

Related Questions