human
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"
Solution in Python:
assistant
#Here is code to program to find weighted median of a given array and the other steps required.
 def weightedMedian ( arr , W ) :
	pairs = [ ]
	for index in range ( len ( arr ) ) :
		pairs . append ( [ arr [ index ] , W [ index ] ] )
	pairs . sort ( key = lambda p : p [ 0 ] )
	if len ( arr ) % 2 != 0 :
		sums = 0
		for element , weight in pairs :
			sums += weight
			if sums > 0.5 :
				print ( " The ▁ Weighted ▁ Median " , end = ' ▁ ' )
				print ( " is ▁ element ▁ { } " . format ( element ) )
	else :
		sums = 0
		for element , weight in pairs :
			sums += weight
			if sums >= 0.5 :
				print ( " Lower ▁ Weighted ▁ Median " , end = ' ▁ ' )
				print ( " is ▁ element ▁ { } " . format ( element ) )
				break
		sums = 0
		for index in range ( len ( pairs ) - 1 , - 1 , - 1 ) :
			element = pairs [ index ] [ 0 ]
			weight = pairs [ index ] [ 1 ]
			sums += weight
			if sums >= 0.5 :
				print ( " Upper ▁ Weighted ▁ Median " , end = ' ▁ ' )
				print ( " is ▁ element ▁ { } " . format ( element ) )
				break
if __name__ == " _ _ main _ _ " :
	arr = [ 4 , 1 , 3 , 2 ]
	W = [ 0.25 , 0.49 , 0.25 , 0.01 ]
	weightedMedian ( arr , W )