Problem:
The task is to reverse the strings contained in each pair of matching parentheses, starting from the innermost pair. The results string should not contain any parentheses.
Example:
>>> s = "a(bc)de"
>>> reverseParentheses(s)
"acbde"
>>> s = "The ((quick (brown) (fox) jumps over the lazy) dog)"
>>> reverseParentheses(s)
"The god quick nworb xof jumps over the lazy"
To achieve this task I have written the following piece of code:
def reverseParentheses(s):
i = 0
brackarray = []
recursivearray = []
a = []
numberofbrack = -1
alteredstring = s
chars = "()"
for char in chars:
alteredstring = alteredstring.replace(char, "")
while i < len(s):
if s[i] == '(':
j = i
numberofbrack = numberofbrack + 1
j = j - numberofbrack
brackarray.append(j)
if s[i] == ')':
m = i
numberofbrack = numberofbrack + 1
m = m- numberofbrack
n = brackarray.pop()
recursivearray.append((n,m))
i = i+1
for item in recursivearray:
lenas = len(alteredstring)
z = recursive(item[0], item[1], alteredstring)
alteredstring1 = alteredstring[0:item[0]]
alteredstring2 = alteredstring[item[1]:lenas]
alteredstring = alteredstring1+z+alteredstring2
return alteredstring
def recursive(start, end, string):
y = string[start:end]
string = y[::-1]
return string
Could somebody please review above code and provide suggestions and improvements?
quick
is inside two levels of parentheses, it gets reversed twice, and thus should still appear asquick
. \$\endgroup\$