Program to find weighted median of a given array | Function to calculate weighted median ; Store pairs of arr [ i ] and W [ i ] ; Sort the list of pairs w . r . t . to their arr [ ] values ; If N is odd ; Traverse the set pairs from left to right ; Update sums ; If sum becomes > 0.5 ; If N is even ; For lower median traverse the set pairs from left ; Update sums ; When sum >= 0.5 ; For upper median traverse the set pairs from right ; Update sums ; When sum >= 0.5 ; Driver Code ; Given array arr [ ] ; Given weights W [ ] ; Function Call
def weightedMedian ( arr , W ) : NEW_LINE INDENT pairs = [ ] NEW_LINE for index in range ( len ( arr ) ) : NEW_LINE INDENT pairs . append ( [ arr [ index ] , W [ index ] ] ) NEW_LINE DEDENT pairs . sort ( key = lambda p : p [ 0 ] ) NEW_LINE if len ( arr ) % 2 != 0 : NEW_LINE INDENT sums = 0 NEW_LINE for element , weight in pairs : NEW_LINE INDENT sums += weight NEW_LINE if sums > 0.5 : NEW_LINE INDENT print ( " The ▁ Weighted ▁ Median " , end = ' ▁ ' ) NEW_LINE print ( " is ▁ element ▁ { } " . format ( element ) ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT sums = 0 NEW_LINE for element , weight in pairs : NEW_LINE INDENT sums += weight NEW_LINE if sums >= 0.5 : NEW_LINE INDENT print ( " Lower ▁ Weighted ▁ Median " , end = ' ▁ ' ) NEW_LINE print ( " is ▁ element ▁ { } " . format ( element ) ) NEW_LINE break NEW_LINE DEDENT DEDENT sums = 0 NEW_LINE for index in range ( len ( pairs ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT element = pairs [ index ] [ 0 ] NEW_LINE weight = pairs [ index ] [ 1 ] NEW_LINE sums += weight NEW_LINE if sums >= 0.5 : NEW_LINE INDENT print ( " Upper ▁ Weighted ▁ Median " , end = ' ▁ ' ) NEW_LINE print ( " is ▁ element ▁ { } " . format ( element ) ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 1 , 3 , 2 ] NEW_LINE W = [ 0.25 , 0.49 , 0.25 , 0.01 ] NEW_LINE weightedMedian ( arr , W ) NEW_LINE DEDENT