The problem here asks me to reverse any string inside (). Let's say if my the string is "foo(bar(baz))blim", then the returned result would be "foobazrabblim" . Someone helped me with the coding process, however, I still don't understand why the code is detecting the outer ) first.
def reverseInParentheses(inputString):
n=len(inputString)
for i in range(n):
if inputString[i] == "(":
start=i
if inputString[i] == ")":
end=i
return reverseInParentheses(inputString[:start]+
inputString[start+1:end][::-1]+inputString[end+1:n])
return inputString
For what I understand, let's say we have "foo(bar(baz))blim". So python detect start=3, end=11. then we call function reverseinparetheses, we will have "foozab(rab)blim". Going through the function again, there is the new start=6, end=10. In the end, we have "foozabbarblim" which is not "foobazrabblim" that we are expecting. I am wondering how is the program detecting the outer ")" first?
It's not detecting the outermost parentheses. It's finding the innermost pair, reversing the inside, and then repeating until there are no more parentheses.
if inputString[i] == ")":
....
This block fires when you've hit the first ')', and at that stage start will be the '(' that opens the first ')'. This is the innermost pair.
Then you have:
return reverseInParentheses(inputString[:start]+inputString[start+1:end][::-1]+inputString[end+1:n])
This reverses the content from start to end (the innermost pair) and then calls the function, cutting off the rest of the for loop.
If you actually print inputString at each step you get:
foo(bar(baz))blim
foo(barzab)blim
foobazrabblim
Innermost parentheses are getting reversed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With