python 数据流中的中位数

'''
题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,
那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,
那么中位数就是所有数值排序之后中间两个数的平均值。
我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

使用插入排序算法
'''
# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.sorted=[]
    def Insert(self, num):
        # write code here
        if len(self.sorted)==0:
            self.sorted.append(num)
        else:
            for i in range(len(self.sorted)):
                if self.sorted[i]>num:
                    self.sorted=self.sorted[:i]+[num]+self.sorted[i:]
                    return
            self.sorted.append(num)
            # 如果遍历完了当前排序好的数组,都没有找到比当前数据流中新加入的元素num数值更大的元素
            # 说明num应该被添加在列表最后
    def GetMedian(self,n=None):
        # write code here
        pos=len(self.sorted)//2
        if len(self.sorted)%2==0:
            return (self.sorted[pos-1]+self.sorted[pos]+0.0)/2
        else:
            return self.sorted[pos]+0.0
if __name__=='__main__':
    a=Solution()
    inp=[5, 2, 3, 4, 1, 6, 7, 0, 8]
    for num in inp:
        a.Insert(num)
        print(a.GetMedian())
    # "5.00 3.50 3.00 3.50 3.00 3.50 4.00 3.50 4.00

猜你喜欢

转载自blog.csdn.net/WYXHAHAHA123/article/details/89924454