human
What is a code to find K elements whose absolute difference with median of array is maximum and the other steps required given the following:
Find K elements whose absolute difference with median of array is maximum | Function for calculating median.
Check for even case.
Function to find the K maximum absolute difference with the median of the array.
Sort the array.
Store median.
Find and store difference.
If diff [ i ] is greater print it . Else print diff [ j ].
Driver code"
How can the above be solved in Python?
assistant
#Here is code to find K elements whose absolute difference with median of array is maximum and the other steps required.
 def findMedian ( a , n ) :
	if ( n % 2 != 0 ) :
		return a [ int ( n / 2 ) ]
	return ( a [ int ( ( n - 1 ) / 2 ) ] + a [ int ( n / 2 ) ] ) / 2.0
def kStrongest ( arr , n , k ) :
	arr . sort ( )
	median = findMedian ( arr , n )
	diff = [ 0 ] * ( n )
	for i in range ( n ) :
		diff [ i ] = abs ( median - arr [ i ] )
	i = 0
	j = n - 1
	while ( k > 0 ) :
		if ( diff [ i ] > diff [ j ] ) :
			print ( arr [ i ] , end = " ▁ " )
			i += 1
		else :
			print ( arr [ j ] , end = " ▁ " )
			j -= 1
		k -= 1
arr = [ 1 , 2 , 3 , 4 , 5 ]
k = 3
n = len ( arr )
kStrongest ( arr , n , k )