human
Write me a code to count pairs with given sum and the other steps required given the following:
Count pairs with given sum | Set 2 | Function to return the count of pairs from arr with the given sum.
To store the count of pairs.
Sort the given array.
Take two pointers.
If sum is greater.
If sum is lesser.
If sum is equal.
Find the frequency of arr [ i ].
Find the frequency of arr [ j ].
If arr [ i ] and arr [ j ] are same then remove the extra number counted.
Return the required answer.
Driver code"
Solution in Python:
assistant
#Here is code to count pairs with given sum and the other steps required.
 def pairs_count ( arr , n , sum ) :
	ans = 0
	arr = sorted ( arr )
	i , j = 0 , n - 1
	while ( i < j ) :
		if ( arr [ i ] + arr [ j ] < sum ) :
			i += 1
		elif ( arr [ i ] + arr [ j ] > sum ) :
			j -= 1
		else :
			x = arr [ i ]
			xx = i
			while ( i < j and arr [ i ] == x ) :
				i += 1
			y = arr [ j ]
			yy = j
			while ( j >= i and arr [ j ] == y ) :
				j -= 1
			if ( x == y ) :
				temp = i - xx + yy - j - 1
				ans += ( temp * ( temp + 1 ) ) // 2
			else :
				ans += ( i - xx ) * ( yy - j )
	return ans
arr = [ 1 , 5 , 7 , 5 , - 1 ]
n = len ( arr )
sum = 6
print ( pairs_count ( arr , n , sum ) )