反转括号内

Reverse Inside Parentheses

大家好,我需要一些有关 python 脚本的帮助。

括号里面需要交替反转。我已经为此苦苦挣扎了 2 个多小时...

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

如果您能提供帮助,我将不胜感激。

您可以遍历输入字符串并将字符添加到 list,只要检查的字符不是括号即可。如果检查的字符是括号,则需要知道到目前为止看到的括号的数量是偶数还是奇数。如果是偶数,可以将 list 中的字符添加到结果中。如果是奇数,则必须将 list 中的字符添加到结果中。在任何一种情况下,您都清空 list,并且需要注意在您 return 结果之前它是空的。

>>> 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'