Question by applying same idea in Python


  • 0
    J

    Re: Java solution using two PriorityQueues

    Hi, I am trying to code in Python. By applying the idea from "Find median from Data Stream" ([https://leetcode.com/problems/find-median-from-data-stream/](link url)). I have found if there was a pair of number appear in the nums, my code would fail. E.g. [1,3,-1,-3]. It would give [1,1]. Can anyone help me correct it? Thanks!!

    '''
    import heapq
    class MedianFinder(object):
    def slidingMedian(self,nums,k):
    small,large,res=[],[],[0]*(len(nums)-k+1)

        for i in range(len(nums)):
            heapq.heappush(small, -heapq.heappushpop(large, nums[i]))
            if len(large) < len(small):
                heapq.heappush(large, -heapq.heappop(small))
    
            if len(large) + len(small)==k:
                if len(large) > len(small):
                    median= float(large[0])
                else:
                    median= float((large[0] - small[0]) / 2.0)
                
                start=i-k+1
                res[start]=median
                
                if (nums[start] in small):
                    small.remove(nums[start])
                elif (-nums[start] in small):
                    small.remove(-nums[start])
                else: large.remove(nums[start])
    
        return res
    

    s=MedianFinder()
    print(s.slidingMedian([1,3,-1,-3],3))
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.