Skip to content

Instantly share code, notes, and snippets.

@praveenvvstgy
Created November 10, 2014 15:46
Show Gist options
  • Save praveenvvstgy/c5d21b00ae425a7afde7 to your computer and use it in GitHub Desktop.
Save praveenvvstgy/c5d21b00ae425a7afde7 to your computer and use it in GitHub Desktop.
Write a function that, given a sentence, along with the position of an opening parenthesis, finds the corresponding closing parenthesis.
openers = "({["
closers = ")}]"
def paranthesis_match(string, pos):
stack = [string[pos]]
for i in range(pos + 1, len(string)):
if string[i] in openers:
stack.append(string[i])
if string[i] in closers:
stack.pop()
if len(stack) == 0:
return i
print paranthesis_match("Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing.", 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment