human
Can you provide a code to length of longest balanced parentheses prefix and the other steps required given the following:
Length of longest balanced parentheses prefix | Function to return the length of longest balanced parentheses prefix ..
Traversing the string ..
If open bracket add 1 to sum ..
If closed bracket subtract 1 from sum.
if first bracket is closing bracket then this condition would help.
If sum is 0 , store the index value ..
Driver Code"
How can the above be solved in Python?
assistant
#Here is code to length of longest balanced parentheses prefix and the other steps required.
 def maxbalancedprefix ( str , n ) :
	_sum = 0
	maxi = 0
	for i in range ( n ) :
		if str [ i ] == ' ( ' :
			_sum += 1
		else :
			_sum -= 1
		if _sum < 0 :
			break
		if _sum == 0 :
			maxi = i + 1
	return maxi
str = ' ( ( ( ) ( ) ) ( ) ) ( ( '
n = len ( str )
print ( maxbalancedprefix ( str , n ) )