human
Number of alternating substrings from a given Binary String | Function to count number of alternating substrings from a given binary string.
Initialize dp array , where dp [ i ] [ j ] stores the number of alternating strings starts with i and having j elements ..
Traverse the string from the end.
If i is equal to N - 1.
Otherwise ,.
Increment count of substrings starting at i and has 0 in the beginning.
Increment count of substrings starting at i and has 1 in the beginning.
Stores the result.
Iterate in the range [ 0 , N - 1 ].
Update ans.
Return the ans.
Driver code.
Given Input.
Function call"
How can the above be solved in Python?
 ... Give me a code to number of alternating substrings from a given Binary String and the other steps required?
assistant
#Here is code to number of alternating substrings from a given Binary String and the other steps required.
 def countAlternatingSubstrings ( S , N ) :
	dp = [ [ 0 for i in range ( N ) ] for i in range ( 2 ) ]
	for i in range ( N - 1 , - 1 , - 1 ) :
		if ( i == N - 1 ) :
			if ( S [ i ] == '1' ) :
				dp [ 1 ] [ i ] = 1
			else :
				dp [ 0 ] [ i ] = 1
		else :
			if ( S [ i ] == '0' ) :
				dp [ 0 ] [ i ] = 1 + dp [ 1 ] [ i + 1 ]
			else :
				dp [ 1 ] [ i ] = 1 + dp [ 0 ] [ i + 1 ]
	ans = 0
	for i in range ( N ) :
		ans += max ( dp [ 0 ] [ i ] , dp [ 1 ] [ i ] )
	return ans
if __name__ == ' _ _ main _ _ ' :
	S = "0010"
	N = len ( S )
	print ( countAlternatingSubstrings ( S , N ) )