human
Find a point whose sum of distances from all given points on a line is K | Function to find the sum of distances of all points from a given point.
Stores sum of distances.
Traverse the array.
Return the sum.
Function to find such a point having sum of distances of all other points from this point equal to K.
If N is odd keep left as arr [ n / 2 ] else keep left as arr [ n / 2 - 1 ] + 1.
.
Keep right as arr [ N - 1 ].
Perform binary search in the right half.
Calculate the mid index of the range.
If temp is equal to K.
Print the value of mid.
If the value of K < temp.
Update right to mid - 1.
If the value of K > temp.
Update left to mid + 1.
Update the value of left.
Update the value of right.
Perform binary search on the left half.
Calculate the mid index of the range.
If temp is equal to K.
Print mid.
if K > temp.
Update right to mid - 1.
If K < temp.
Update left to mid + 1.
If no such point found.
Driver Code"
How can the above be solved in Python?
 ... Write me a code to find a point whose sum of distances from all given points on a line is K and the other steps required?
assistant
#Here is code to find a point whose sum of distances from all given points on a line is K and the other steps required.
 def findSum ( arr , N , pt ) :
	sum = 0
	for i in range ( N ) :
		sum += abs ( arr [ i ] - pt )
	return sum
def findPoint ( arr , N , K ) :
	left = 0
	if ( N % 2 ) :
		left = arr [ N // 2 ]
	else :
		left = arr [ N // 2 - 1 ] + 1
	right = arr [ N - 1 ]
	while ( left <= right ) :
		mid = ( left + right ) // 2
		temp = findSum ( arr , N , mid )
		if ( temp == K ) :
			print ( mid )
			return
		elif ( K < temp ) :
			right = mid - 1
		else :
			left = mid + 1
	left = arr [ 0 ]
	right = arr [ N // 2 ] - 1
	while ( left <= right ) :
		mid = ( left + right ) // 2
		temp = findSum ( arr , N , mid )
		if ( temp == K ) :
			print ( mid )
			return
		elif ( K > temp ) :
			right = mid - 1
		else :
			left = mid + 1
	print ( " - 1" )
if __name__ == ' _ _ main _ _ ' :
	arr = [ 1 , 3 , 6 , 7 , 11 ]
	K = 18
	N = len ( arr )
	findPoint ( arr , N , K )