简体   繁体   中英

How can i find the median of a number from a list? Python

I'm trying to find the median in a list. The equation to find the median is N terms/2. The code i've tried is to find and index the number but when i index i get 0 or an error, why is this?

def Median():
#MedianList_Str = ""
MedianList = [2,4,6]
print("What number do you want to add to the array, enter 0 to exit")
try:
    Int = int(input())
    if Int == 0:
        QuitApp()
    else:
       MedianList.append(Int)
except:
    print("Please enter a number")

MedianT = math.floor(len(MedianList)/2) #finds the nth term 
MedianList.sort #sorts the list so you can find the median term
MedianList_Str.join(MedianList)

this is what i've done. I've also tried index

def Median():
MedianList_Str = ""
MedianList = [2,4,6]
print("What number do you want to add to the array, enter 0 to exit")
try:
    Int = int(input())
    if Int == 0:
        QuitApp()
    else:
       MedianList.append(Int)
except:
    print("Please enter a number")

MedianT = math.floor(len(MedianList)/2) #finds the nth term 
MedianList.sort #sorts the list so you can find the median term
print(MedianList.index(MedianT))

which gets me 0

what can i do to get me the median? I understand that there already exists such a question but i want to try a different way.

Here's a nice trick to avoid using if / else to handle the odd and even length cases separately: the indices in the middle are (len(nums) - 1) // 2 and len(nums) // 2 . If the length is odd, then these indices are equal, so adding the values and dividing by 2 has no effect.

Note that you should do floor-division with the // operator to get an integer to use as an index.

def median(nums):
    nums = sorted(nums)
    middle1 = (len(nums) - 1) // 2
    middle2 = len(nums) // 2
    return (nums[middle1] + nums[middle2]) / 2

Examples:

>>> median([1, 2, 3, 4])
2.5
>>> median([1, 2, 3, 4, 5])
3.0

As others have mentioned, I would used sorted(MedianT) instead of MeadianT.sort() .

In addition, use array based indexing instead of the .index() function.
For example, this:

print(MedianList[MedianT])

Instead of this:

print(MedianList.index(MedianT))

I have included below with comments the logic and thought process of finding median value of an array in Python.

def median(array):
    length = len(array)
    sorted_arr = sorted(array) # sorting in O(n) time or linear complexity
    # we are subtracting 1 from overall 
    # length because indexing is 0-based
    # essentially indexes of arrays start at 0
    # while counting length starts at 1
    # idx_norm = (length-1) / 2 # using only single division operator yields a float
    idx = (length-1) // 2 # using floor division operator // yields an Int which can be used for index

    # we run a simple condition to see 
    # whether if the overall length of array
    # is even or odd.
    # If odd then we can use index value (idx) to find median
    # we use modulus operator to see if if there is any remainder
    # for a division operation by 2. If remainder equals 0 then
    # array is even. If not array is odd.
    if length % 2 == 0:
        return (sorted_arr[idx] + sorted_arr[idx + 1]) / 2.0 # if you need an Int returned, then wrap this operation in int() conversion method
    else:
        return sorted_arr[idx]
    # If even we have to use index value (idx) and the next index value (idx + 1)
    # to create total and then divide for average

a = [1, 2, 3, 4, 12, 1, 9] # 7 elements, odd length --> return 3
b = [2, 3, 7, 6, 8, 9] # 6 elements, even length --> return 6.5

median(a)
median(b)

Please let me know if you have any questions and hope this helps. Cheers!

The median is either the middle element by value , or the average of the middle two if the length of the array is even.

So first we must sort the array, and then apply our logic.

def median(l):
    l = sorted(l)
    middle = len(l) // 2
    return l[middle] if len(l) % 2 == 1 else (l[middle - 1] + l[middle]) / 2

Note that there exist more efficient algorithms to find the median, that take O(n) instead of O(n log n) time, however they're not trivial to implement and are not available in Python's standard library.

I created a class. You can add elements to your list with the addNum method. The findMedian method will check if the length of the list is odd or even and will give you the median depending on the situation.

class MedianFinder:
    def __init__(self):
        num_list = []
        self.num_list = num_list

    def addNum(self, num):
        self.num_list.append(num)
        return self.num_list

    def findMedian(self):
        # Check len of list
        if len(self.num_list) % 2 == 0:
            l = int(len(self.num_list) / 2)
            return (self.num_list[l - 1] + self.num_list[l]) / 2

        else:
            l = math.floor(len(li) / 2)
            return self.num_list[l]

Example usage;

s.addNum(2)
s.addNum(4)
s.addNum(6)
s.addNum(8)
print(s.findMedian())

Output: 5.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM