-3

I am trying to extract what's between parenthesis (including parenthesis) recursively.

This is my solution:

def paren(txt):
  if txt[1] == ")":
    return ''
  if txt[0] == "(":
    if len(txt) > 2:
        return txt[1]  + paren(txt[:1] + txt[2:])
    return txt[1]
  if len(txt) > 2:
    return paren(txt[1:])
  return ""

But it doesn't include any parenthesis. How can I fix it?

Example:

print paren("h(ello)o")
Output: (ello)
print paren("(hello)")
Output: (hello)
Zee
  • 31
  • 3
  • 2
    So are you trying to find the text inside the innermost set of parentheses? – JPeroutek Jul 29 '15 at 15:16
  • Can you give an example before and after of what you want this to do? – Rich Sala Jul 29 '15 at 15:18
  • 1
    Will there only be one set of parenthesis? What should happen here: `'(h(ello))'`? – kylieCatt Jul 29 '15 at 15:28
  • @IanAuld let's assume there is only one set of parenthesis. – Zee Jul 29 '15 at 15:29
  • 1
    possible duplicate of [Regular expression to return text between parenthesis](http://stackoverflow.com/questions/4894069/regular-expression-to-return-text-between-parenthesis) – kylieCatt Jul 29 '15 at 15:30
  • 1
    @Zee please update your question. Also what do you mean by saying 'extract what's between parenthesis recursively`? If there is only one set of parenthesis then I do not understand why you want to do it recursively – Alik Jul 29 '15 at 15:30
  • @Zee assuming there is only one pair of parenthesis check my solution – Halcyon Abraham Ramirez Jul 29 '15 at 15:33

2 Answers2

2

If you have a single pair of parenthesis, I would recommend to go with Halcyon Abraham Ramirez's answer. Otherwise, try this method:

def paren(text):
    pstack = 0
    start = 0
    end = len(text)
    for i, c in enumerate(text):
        if c == '(':
            if pstack == 0:
                start = i
            pstack += 1
        elif c == ')':
            pstack -= 1
            if pstack == 0:
                end = i
                break

    return text[start:end]

And here is an example:

>>> paren("h(ello)")
'(ello)'

If you do not need the root parenthesis, you can modify the return statement like this:

return text[start+1:end-1]

And again:

>>> paren("h(ello)")
'ello'
Community
  • 1
  • 1
bagrat
  • 6,740
  • 4
  • 27
  • 47
2

use index

word = "hehlllllllll(ooooo)jejejeje"

def extract(word):
    return word[word.index("("):word.index(")") + 1]

output:

(ooooo)

taking it further. if there are multiple parenthesis:

a = "h((el(l))o"

def extract_multiple_parenthesis(word):
    closing_parenthesis = word[::-1].index(")")
    last_parenthesis_index = (len(word) - closing_parenthesis)
    return  word[word.index("("):last_parenthesis_index]  

output:

((el(l))
Halcyon Abraham Ramirez
  • 1,398
  • 1
  • 15
  • 17