我正在创建一个程序,它会分割括号以分开对#'。例如,()()
变为|()|()|
但(())
保持不变,为|(())|
。它保持'得到'同一个角色。我尝试更改我插入的位置,例如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 + 1
和pos -1
,但效果不大,而不是重复。
答案 0 :(得分:3)
在这种情况下,使用“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)|
虽然使用递归函数会更清晰,更容易,但我想向您展示如何修复现有代码中的错误,而不是完全改变您的思维过程......
答案 1 :(得分:1)
在迭代它时修改一个对象总是一个灾难的处方。
你需要在迭代旧对象时建立一个新对象:
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)|
答案 2 :(得分:0)
你不想改变你正在迭代的东西。我已经通过创建输入字符串的副本来修复您的代码,它似乎正在工作:
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)|