Home > Software engineering >  Reverse Inside Parentheses
Reverse Inside Parentheses

Time:03-15

Hi guys I need some help with a python script.

Inside of the parantheses need to be reversed alternately. I've been struggling with this for over 2 hours...

def reverse(string):
    counter = 0
    res = [""]
    for i in string:
            
        if i == "(":
            res.append("")
            counter = counter   1
            print(res, counter)
                
        elif i == ")":
            counter = counter - 1
                
            if counter % 2 == 0:
                res[counter]  = res.pop()
                print(res, counter)
            else:
                res[counter] = res[counter]   res.pop()  
                print(res, counter)       
        elif counter % 2 == 0:
            res[counter]  = i
            print(res, counter)
        else:
            res[counter] = i   res[counter]
            print(res, counter)
    return res[0]
INPUT: E(ev(ry)ht)i(gn)
EXPECTED OUTPUT: Everything

OUTPUT:
['E', 'very'] 1
['E', 'hvery'] 1
['E', 'thvery'] 1
['Ethvery'] 0
['Ethveryi'] 0
['Ethveryi', ''] 1
['Ethveryi', 'g'] 1
['Ethveryi', 'ng'] 1
['Ethverying'] 0

I'd really appreciate if you helped.

CodePudding user response:

You can iterate through the input string and add the character to a list as long as the examined character is not a parenthesis. If the examined character is a parenthesis, you need to know if the number of parentheses seen so far is even or odd. If it is even, you can add the characters in the list to the result. If it is odd, you have to add the characters in the list reversed to the result. In either case, you empty the list, and need to take care that it's empty before you return your result.

>>> def reverse(a_string):
...     seen_even = True
...     temp, result = [], []
...     for c in a_string:
...         if c not in ('(',')'):
...            temp.append(c)
...         else:
...            if seen_even:
...                result.extend(temp)
...            else:
...                result.extend(temp[::-1])
...            seen_even = not seen_even
...            temp = []
...     if temp: # e.g., 'Everything', 'Everythi)gn'
...         if seen_even:
...             result.extend(temp)
...         else:
...             result.extend(temp[::-1])
...     return ''.join(result)
... 
>>> inp_string = 'E(ev(ry)ht)i(gn)'
>>> reverse(inp_string)
'Everything'
  • Related