Here's a general purpose library function I've created for you
def makePairs(code: str, bracket_list = ['[', '{', '(', '<']) -> dict:
"""
Pair Maker
=========
Finds and creates corresponding pairs of all types of brackets given in the 'bracket_list' present in the 'code'.
Parameters
----------
1. Code : str - given string of code
2. Bracket List : list - all types of brackets whose pair has to be searched and mapped
Returns
-------
A dictionary that maps an opening bracket position to corresponding closing bracket position
Example
-------
>>> bracePairs = makePairs(code)\n
>>> for open, close in bracePairs.items():\n
>>> print(code[open : close+1])
"""
naivePairs = { '{':'}', '[':']', '(':')', '<':'>' }
pairs:dict = {} # maps '{' position to corresponding '}' position
openBraceStack = [] # will store the consecutive brace openings
for pos, char in enumerate(code):
if char in naivePairs.keys(): openBraceStack.append(pos) # if char is '{', push it into the 'openBraceStack'
elif char in naivePairs.values(): pairs[openBraceStack.pop()] = pos # if char is '}', pop the last '{' from 'openBraceStack' and store this pair into 'pairs'
return pairs
Usage (Have also provided in it's docstring):
bracePairs = makePairs(code)
for open, close in bracePairs.items():
print(code[open : close+1], '\n\n\n')
Query specific usage:
bracePairs = makePairs(code)
cakeOpen = code.find('{', code.find('fun cake')) # find the first '{' after cake function
cakeCode = code[cakeOpen + 1 : bracePairs[cakeOpen]]
print(cakeCode)