Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Programming questions