'I have a problem with the task of reversing words and removing parentheses

Task

Write a program that will decode the secret message by reversing text between square brackets. The message may contain nested brackets (that is, brackets within brackets, such as One[owT[Three[ruoF]]]). In this case, innermost brackets take precedence, similar to parentheses in mathematical expressions, e.g. you could decode the aforementioned example like this:

  1. One[owT[Three[ruoF]]]
  2. One[owT[ThreeFour]]
  3. One[owTruoFeerhT]
  4. OneThreeFourTwo

In order to make your own task slightly easier and less tricky, you have already replaced all whitespaces in the original text with underscores (“_”) while copying it from the paper version.

Input description

The first and only line of the standard input consists of a non-empty string of up to 2 · 106 characters which may be letters, digits, basic punctuation (“,.?!’-;:”), underscores (“_”) and square brackets (“[]”). You can safely assume that all square brackets are paired correctly, i.e. every opening bracket has exactly one closing bracket matching it and vice versa.

Output description

The standard output should contain one line – the decoded secret message without any square brackets.

Example

For sample input:

A[W_[y,[]]oh]o[dlr][!]

the correct output is:

Ahoy,_World!

Explanation

This example contains empty brackets. Of course, an empty string, when reversed, remains empty, so we can simply ignore them. Then, as previously, we can decode this example in stages, first reversing the innermost brackets to obtain A[W_,yoh]o[dlr][!]. Afterwards, there are no longer any nested brackets, so the remainder of the task is trivial.

Below is my program that doesn't quite work

word = input("print something: ")
word_reverse = word[::-1]
while("[" in word and "]" in word):
    open_brackets_index = word.index("[")
    close_brackets_index = word_reverse.index("]")*(-1)-1
    # print(word)
    # print(open_brackets_index)
    # print(close_brackets_index)
    reverse_word_into_quotes = word[open_brackets_index+1:close_brackets_index:][::-1]
    word = word[:close_brackets_index]
    word = word[:open_brackets_index]
    word = word+reverse_word_into_quotes
    word = word.replace("[","]").replace("]","[")
    print(word)

print(word)

Unfortunately my code only works with one pair of parentheses and I don't know how to fix it.

Thank you in advance for your help



Solution 1:[1]

I realize the my previous answer has been accepted but, for completeness, I'm submitting a second solution that does NOT use the re module:

text = 'A[W_[y,[]]oh]o[dlr][!]'

def find_pattern(text):
    #  Find [...] and return the locations of [ (start) ] (end)
    #  and the in-between str (content) 
    content = ''
    for i,c in enumerate(text):
        if c == '[':
            content = ''
            start = i
        elif c == ']':
            end = i
            return start, end, content
        else:
            content += c
    return None, None, None

while True:
    start, end, content = find_pattern(text)
    if start is None:
        break
    #  Replace the content between [] with its reverse
    text = "".join((text[:start], content[::-1], text[end+1:]))
print(text)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 C. Pappy