Search code examples
pythontext-parsing

python code to get ending brace index from list


I have my input list of strings where I need to pass the index of any opening brace and expecting my python function to return its corresponding closing brace's index and its value.

Input list :

mylist=[
'a',
'b(',
'(',
'cd',
'd(e)',
'hi)',
'last brace) '
]

I need get the index and the string of the list

getindex=func(mylist[2])

getindex should have hi) with index 5. It should ignore any corresponding balanced braces inbetween ex: d(e) or the last brace) ,etc.

getindex=(5,'hi)')

I am little new to python and appreciate your time in help me.Thanks!


Solution

  • You just need to count the left brace start from start line, when meet left brace, increase it, when meet right brace, decrease it. when it reach zero again, you find the correct index.

    Sample code for you:

    def get_closing_brace_index(str_list, left_idx):
        # input check, you can ignore it if you assure valid input
        if left_idx < 0 or left_idx >= len(str_list) or '(' not in str_list[left_idx]:
            return -1, ''
    
        # use a left brace counter
        left_count = 0
        # just ignore everything before open_brace_index
        for i, s in enumerate(str_list[left_idx:]):
            for c in s:
                if c == '(':
                    left_count += 1
                elif c == ')':
                    left_count -= 1
                    # find matched closing brace
                    if left_count == 0:
                        return i + left_idx, str_list[i + left_idx]
                    # invalid brace match
                    elif left_count < 0:
                        return -1, ''
        return -1, ''
    
    def test():
        mylist = [
            'a',
            'b(',
            '(',
            'cd',
            'd(e)',
            'hi)',
            'last brace) '
        ]
    
        print(get_closing_brace_index(mylist, 1))
        # output (6, 'last brace) ')
        print(get_closing_brace_index(mylist, 2))
        # output (5, 'hi)')
        print(get_closing_brace_index(mylist, 4))
        # output (4, 'd(e)')
        print(get_closing_brace_index(mylist, 0))
        # output (-1, '')
        print(get_closing_brace_index(mylist, 6))
        # output (-1, '')
    

    Hope that help you.