I am writing a program to reverse the substrings enclosed in parenthesis in python. The resultant string should not contain any parenthesis. I am printing b1 and b2 and ch for testing purposes. It seems that in the second iteration of the for loop inside the while loop, the b1 variable is not updated with the correct index. I tried to write a solution like below:
def reverseParentheses(s):
r = s
sstring = ''
astring = ''
b1 = b2 = 0
count = 0
for ch in s:
if ch == '(':
count+=1
elif ch ==')':
count+=1
else:
pass
while True:
b1 = b2 = 0
for ch in r:
if ch == '(':
b1 = r.index(ch)
print("b1= ",b1, ch)
if ch == ')':
b2 = r.index(ch)
print("b2= ",b2, ch)
sstring = r[b2-1:b1:-1]
print(r)
print(sstring)
astring = r[0:b1]+sstring+r[b2+1:]
print(astring)
r = astring
break
if len(astring)+count == len(s):
break
return r
s = "a(bcdefghijkl(mno)p)q"
print(reverseParentheses(s))
This is the output that I get: aonmpbcdefghijklq This is the output I expect: apmnolkjihgfedcbq