Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """
- Return the string with reversing parts inside parentheses.
- Solution for problem from CodeSignal.
- """
- def reverse_in_parentheses(s: str, is_reverse: bool = False) -> str:
- """
- s must be well-formed.
- """
- j = s.find('(')
- if j == -1:
- return (''.join(reversed(s)) if is_reverse
- else s)
- pieces = []
- count = 0
- i = 0
- while j < len(s):
- if s[j] == '(':
- if count == 0: # add part without parentheses
- pieces.append(reverse_in_parentheses(s[i:j], is_reverse))
- i = j
- count += 1
- elif s[j] == ')':
- count -= 1
- if count == 0: # add '...' from part '(...)'
- piece = reverse_in_parentheses(
- reverse_in_parentheses(s[i + 1:j], True),
- is_reverse)
- pieces.append(piece)
- i = j + 1
- j += 1
- pieces.append(reverse_in_parentheses(s[i:j], is_reverse)) # add remain
- return ''.join(reversed(pieces) if is_reverse
- else pieces)
- def main() -> None:
- datas = (
- ('abc', 'abc'),
- ('(bar)', 'rab'),
- ('foo(bar)baz', 'foorabbaz'),
- ('foo(bar)baz(blim)', 'foorabbazmilb'),
- ('foo(bar(baz))blim', 'foobazrabblim'),
- ('', ''),
- ('()', ''),
- ('(abc)d(efg)', 'cbadgfe'),
- ('((ab)cd)', 'dcab'),
- ('foo(bar(baz))blim', 'foobazrabblim')
- )
- for data_input, data_output in datas:
- print(f'"{data_input}" "{data_output}"', end=' ')
- result = reverse_in_parentheses(data_input)
- print(f'"{result}"')
- assert data_output == result
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement