For-loop returns 解析中的相同字符

For-loop returns same character in parsing

我正在创建一个程序,它将拆分 'separate pairs' 的括号。例如 ()() 变为 |()|()|(()) 保持不变,即 |(())|。它保持 'getting' 相同的字符。我已经尝试更改 我插入 的位置,例如 pos - 1,但它仍然不起作用。这是我的代码:

def insert(source_str, insert_str, pos):
        return source_str[:pos]+insert_str+source_str[pos:]


x = 0 
rightSideOfEquation = "()bx((x))c(y(c+1)(x)y)"


for pos in range(len(rightSideOfEquation)):
    if x == 0:
        rightSideOfEquation = insert(rightSideOfEquation,'|',pos)
    if rightSideOfEquation[pos] == '(':
        x += 1
    if rightSideOfEquation[pos] == ')':
        x -= 1

print(rightSideOfEquation)

它打印 |||||||||||||||||||||||()bx((x))c(y(c+1)(x)y)
我想让它打印 |()|bx|((x))|c|(y(c+1)(x)y)|

注意:您可以在此处查看: **https://math.stackexchange.com/questions/1682322/recursive-parsing-parenthesis-with-explanation
**我已经尝试将其更改为 pos + 1pos -1 但收效甚微,除了重复的地方。

你不想改变你正在迭代的东西。我已经通过创建输入字符串的副本修复了您的代码,它似乎可以正常工作:

def insert(source_str, insert_str, pos):
    return source_str[:pos]+insert_str+source_str[pos:]


x = 0 
rightSideOfEquation = "a()bx((x))c(y(c+1)(x)y)"
copy = rightSideOfEquation
posincopy = 0

for pos in range(len(rightSideOfEquation)):
    if rightSideOfEquation[pos] == '(':
        x += 1
        if x == 1:
            copy = insert(copy,'|',posincopy)
            posincopy = posincopy + 1
    if rightSideOfEquation[pos] == ')':
        x -= 1
        if x == 0:
            copy = insert(copy,'|',posincopy + 1)
            posincopy = posincopy + 1
    posincopy = posincopy + 1

print(copy)

输出:

a|()|bx|((x))|c|(y(c+1)(x)y)|

在这种情况下,使用 "while" 语句而不是 for 循环会使您的生活更轻松:

def insert(source_str, insert_str, pos):
    return source_str[:pos]+insert_str+source_str[pos:]

x = 0 
rightSideOfEquation = "a()bx((x))c(y(c+1)(x)y)"
pos = 0

while pos < len(rightSideOfEquation):
  if rightSideOfEquation[pos] == '(':
      if x==0:        
          rightSideOfEquation = insert(rightSideOfEquation,'|',pos)
          pos+=1
      x += 1
  elif rightSideOfEquation[pos] == ')':
      x -= 1
      if x == 0:
          rightSideOfEquation = insert(rightSideOfEquation,'|',pos + 1)
  pos+=1

print(rightSideOfEquation)

这将打印以下内容:

a|()|bx|((x))|c|(y(c+1)(x)y)|

尽管使用递归函数会更简洁、更容易,但我想向您展示如何修复现有代码中的错误,而不是完全改变您的思维过程...

在遍历对象时修改对象总是导致灾难。

您需要在遍历旧对象的同时构建一个新对象:

equation = "a()bx((x))c(y(c+1)(x)y)"
new_equation = []
parens = 0
for ch in equation:
    if ch == '(':
        if parens == 0:
            new_equation.append('|')
        new_equation.append(ch)
        parens += 1
    elif ch == ')':
        new_equation.append(ch)
        parens -= 1
        if parens == 0:
            new_equation.append('|')
    else:
        new_equation.append(ch)
equation = ''.join(new_equation)
print(equation)

给出:

a|()|bx|((x))|c|(y(c+1)(x)y)|