Created
May 16, 2018 03:04
-
-
Save gabraganca/f4bb29ec070aa554cb661aaadb7d98b2 to your computer and use it in GitHub Desktop.
Get position of closing bracket if the poisition of the opening bracket is given.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_closing_index(string, index): | |
""" | |
Get position of closing bracket of a opening | |
bracket given by `index`. | |
Parameters | |
---------- | |
string: str; | |
Input text. | |
index: int; | |
Position of opening bracket | |
Returns | |
------- | |
closing_index: int; | |
Poisition of closing bracket | |
""" | |
# Check if position given corrsponds to a open bracket | |
assert string[index] == '[', 'index does not point to opening bracket' | |
control = 0 # Variable to control number of brackets | |
# Note that we start the loop on index given forward | |
for n, char in enumerate(string[index:]): | |
if char == '[': | |
control += 1 | |
elif char == ']': | |
control -= 1 | |
# If stack is empty, returns position | |
if control == 0: | |
return index+n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment