Question: I am creating a function that checks the index of the close bracket of the same type when the index of an open bracket is

I am creating a function that checks the index of the close bracket of the same type when the index of an open bracket is given. When there is no close bracket, then -1 will be returned.

For example:

'[([)]' is a strong.

[

I give index 0, so the bracket is '[', I am supposed to return the next ']' in the string.

My code is:

def matching_bracket(expr, idx):

bracket_type = expr[idx]

if bracket_type == '(':

return expr[idx:].find(')')+idx

elif bracket_type == '[':

return expr[idx:].find(']')+idx

elif bracket_type =='{':

return expr[idx:].find('}')+idx

elif bracket_type == '<':

return expr[idx:].find('>')

else:

return -1

It works perfectly.

However, if I change it to recursion, my code becomes:

def matching_bracket(expr, idx):

bracket_type = expr[idx]

if len(expr)==0:

return -1

if bracket_type == '(':

if expr[idx+1] == ')':

return idx+1

else:

return matching_bracket(expr[1:], idx-1)

elif bracket_type == '[':

if expr[idx+1] == ')':

return idx+1

else:

return matching_bracket(expr[1:], idx-1)

elif bracket_type =='{':

if expr[idx+1] == ')':

return idx+1

else:

return matching_bracket(expr[1:], idx-1)

elif bracket_type == '<':

if expr[idx+1] == ')':

return idx+1

else:

return matching_bracket(expr[1:], idx-1)

After changing my code to recursion, it stopped working. It returns nothing when I test the function.

Something must have went wrong for my recursion code.

Hope to be enlightened. Thank you.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!