to find the mean max of the heap

45 Views Asked by At
I number : insert number to the q
<br/> D 1 : Delete the max value from heapq
<br/> D -1: Delete the min value from heapq  

This is the condition
so when

[I 16,D 1]   return [0,0]
[I 7,I 5,I -5,D -1] return [7,5]

I tried it with this way but some test case is not passed
is there why to fix this code and if there is better approach let me know

import heapq

def solution(operations):
    answers = []
    answer_max = []
    answer_min = []
    arr_max = []
    arr_min = []
    try:
        for ope in operations:
            o,n=ope.split(" ")
            n = int(n)
            if o=='I':
                heapq.heappush(answer_max,(n,n))
                heapq.heappush(answer_min,(-n,n))
            elif o=='D':
                if n==-1:
                    if len(answer_min)==0: continue
                    else:
                        if len(answer_min)==1:heapq.heappop(answer_min)
                    heapq.heappop(answer_max)
                elif n==1:
                    if len(answer_max)==0: continue
                    else:
                        if len(answer_max)==1: heapq.heappop(answer_max)
                    heapq.heappop(answer_min)
        arr_min = [a[1] for a in answer_min]
        arr_max = [a[1] for a in answer_max]
        
        arr_max = [a for a in arr_max if a in arr_min]
        answers = [arr_min[0], arr_max[0]]
        return answers
    except: return [0,0]
0

There are 0 best solutions below