0

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.

portinesty
  • 13
  • 2
  • Do you want to know : https://stackoverflow.com/questions/931092/reverse-a-string-in-python or do you want to know what is wrong with your code? – JonSG Mar 14 '22 at 19:35
  • I want to make it so the word doesn't get jumbled up in the output – portinesty Mar 14 '22 at 19:44

1 Answers1

0

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'
Nikolaos Chatzis
  • 1,947
  • 2
  • 8
  • 17