-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 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
  • 7,158
  • 6
  • 29
  • 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,520
  • 1
  • 16
  • 17