human
Write me a code to median of two sorted arrays of same size and the other steps required given the following:
Median of two sorted arrays of same size | This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements.
Since there are 2 n elements , median will be average of elements at index n - 1 and n in the array obtained after merging ar1 and ar2.
Below is to handle case where all elements of ar1 [ ] are smaller than smallest ( or first ) element of ar2 [ ].
Below is to handle case where all elements of ar2 [ ] are smaller than smallest ( or first ) element of ar1 [ ].
equals sign because if two arrays have some common elements.
Store the prev median.
Store the prev median.
Driver code to test above function"
How can the above be solved in Python?
assistant
#Here is code to median of two sorted arrays of same size and the other steps required.
 def getMedian ( ar1 , ar2 , n ) :
	i = 0
	j = 0
	m1 = - 1
	m2 = - 1
	count = 0
	while count < n + 1 :
		count += 1
		if i == n :
			m1 = m2
			m2 = ar2 [ 0 ]
			break
		elif j == n :
			m1 = m2
			m2 = ar1 [ 0 ]
			break
		if ar1 [ i ] <= ar2 [ j ] :
			m1 = m2
			m2 = ar1 [ i ]
			i += 1
		else :
			m1 = m2
			m2 = ar2 [ j ]
			j += 1
	return ( m1 + m2 ) / 2
ar1 = [ 1 , 12 , 15 , 26 , 38 ]
ar2 = [ 2 , 13 , 17 , 30 , 45 ]
n1 = len ( ar1 )
n2 = len ( ar2 )
if n1 == n2 :
	print ( " Median ▁ is ▁ " , getMedian ( ar1 , ar2 , n1 ) )
else :
	print ( " Doesn ' t ▁ work ▁ for ▁ arrays ▁ of ▁ unequal ▁ size " )