fork download
  1. import re
  2.  
  3. def remove_parentheses(s):
  4. s = s.replace('()', '') # Bonus!
  5. opens = [m.start() for m in re.finditer(r'\(', s)]
  6. closes = [m.start() for m in re.finditer(r'\)', s)]
  7. pairs = []
  8. while opens:
  9. open = opens.pop()
  10. close = [c for c in closes if c > open][0]
  11. closes.remove(close)
  12. pairs.append((open, close))
  13. nested = sorted([(a, b) for a, b in pairs if (a + 1, b - 1) in pairs])
  14. while nested:
  15. open, close = nested.pop()
  16. s = s[:open] + s[open + 1:close] + s[close + 1:]
  17. nested = [(a, b if b < close else b - 2) for a, b in nested]
  18. return s or 'NULL'
  19.  
  20.  
  21. print(remove_parentheses('((a((bc)(de)))f)'))
  22. print(remove_parentheses('(((zbcd)(((e)fg))))'))
  23. print(remove_parentheses('ab((c))'))
  24. print(remove_parentheses('()'))
  25. print(remove_parentheses('((fgh()()()))'))
  26. print(remove_parentheses('()(abc())'))
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
((a((bc)(de)))f)
((zbcd)((e)fg))
ab(c)
NULL
(fgh)
(abc)