human
Can you provide a code to given an array A [ ] and a number x , check for pair in A [ ] with sum as x and the other steps required given the following:
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Set 2 | Function to check if the array has 2 elements whose sum is equal to the given value.
Sort the array in increasing order.
Traverse the array , nums [ ].
Store the required number to be found.
Perform binary search.
Store the mid value.
If nums [ mid ] is greater than x , then update high to mid - 1.
If nums [ mid ] is less than x , then update low to mid + 1.
Otherwise.
If mid is equal i , check mid - 1 and mid + 1.
Otherwise , prthe pair and return.
If no such pair is found , then pr - 1.
Driver Code.
Function Call"
How can the above be solved in Python?
assistant
#Here is code to given an array A [ ] and a number x , check for pair in A [ ] with sum as x and the other steps required.
 def hasArrayTwoPairs ( nums , n , target ) :
	nums = sorted ( nums )
	for i in range ( n ) :
		x = target - nums [ i ]
		low , high = 0 , n - 1
		while ( low <= high ) :
			mid = low + ( ( high - low ) // 2 )
			if ( nums [ mid ] > x ) :
				high = mid - 1
			elif ( nums [ mid ] < x ) :
				low = mid + 1
			else :
				if ( mid == i ) :
					if ( ( mid - 1 >= 0 ) and nums [ mid - 1 ] == x ) :
						print ( nums [ i ] , end = " , ▁ " )
						print ( nums [ mid - 1 ] )
						return
					if ( ( mid + 1 < n ) and nums [ mid + 1 ] == x ) :
						print ( nums [ i ] , end = " , ▁ " )
						print ( nums [ mid + 1 ] )
						return
					break
				else :
					print ( nums [ i ] , end = " , ▁ " )
					print ( nums [ mid ] )
					return
	print ( - 1 )
if __name__ == ' _ _ main _ _ ' :
	A = [ 0 , - 1 , 2 , - 3 , 1 ]
	X = - 2
	N = len ( A )
	hasArrayTwoPairs ( A , N , X )