Advertisement
OPiMedia

reverse_in_parentheses

Feb 20th, 2021
1,176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. """
  4. Return the string with reversing parts inside parentheses.
  5.  
  6. Solution for problem from CodeSignal.
  7. """
  8.  
  9.  
  10. def reverse_in_parentheses(s: str, is_reverse: bool = False) -> str:
  11.     """
  12.    s must be well-formed.
  13.    """
  14.     j = s.find('(')
  15.     if j == -1:
  16.         return (''.join(reversed(s)) if is_reverse
  17.                 else s)
  18.  
  19.     pieces = []
  20.     count = 0
  21.     i = 0
  22.     while j < len(s):
  23.         if s[j] == '(':
  24.             if count == 0:  # add part without parentheses
  25.                 pieces.append(reverse_in_parentheses(s[i:j], is_reverse))
  26.                 i = j
  27.             count += 1
  28.         elif s[j] == ')':
  29.             count -= 1
  30.             if count == 0:  # add '...' from part '(...)'
  31.                 piece = reverse_in_parentheses(
  32.                     reverse_in_parentheses(s[i + 1:j], True),
  33.                     is_reverse)
  34.                 pieces.append(piece)
  35.                 i = j + 1
  36.  
  37.         j += 1
  38.  
  39.     pieces.append(reverse_in_parentheses(s[i:j], is_reverse))  # add remain
  40.  
  41.     return ''.join(reversed(pieces) if is_reverse
  42.                    else pieces)
  43.  
  44.  
  45. def main() -> None:
  46.     datas = (
  47.         ('abc', 'abc'),
  48.         ('(bar)', 'rab'),
  49.         ('foo(bar)baz', 'foorabbaz'),
  50.         ('foo(bar)baz(blim)', 'foorabbazmilb'),
  51.         ('foo(bar(baz))blim', 'foobazrabblim'),
  52.         ('', ''),
  53.         ('()', ''),
  54.         ('(abc)d(efg)', 'cbadgfe'),
  55.         ('((ab)cd)', 'dcab'),
  56.         ('foo(bar(baz))blim', 'foobazrabblim')
  57.     )
  58.  
  59.     for data_input, data_output in datas:
  60.         print(f'"{data_input}" "{data_output}"', end=' ')
  61.         result = reverse_in_parentheses(data_input)
  62.         print(f'"{result}"')
  63.  
  64.         assert data_output == result
  65.  
  66.  
  67. if __name__ == '__main__':
  68.     main()
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement