1.给定一个如下格式的字符串,(1,(2,3),(4,(5,6),7)),括号内的元素可以是数字,也可以是另一个括号,实现一个算法消除嵌套的括号,例如把上面的表达式变成(1,2,3,4,5,6,7),如果表达式有误,那么报错
2.代码如下:
def removeNestedPare(strs):
if strs == None:
return None
#用来记录不匹配的(出现的次数
Parentheses_num = 0
if list(strs)[0] != '(' or list(strs)[-1] !=')':
return None
sb = '('
for i in range(len(strs)):
ch = list(strs)[i]
if ch == "(":
Parentheses_num += 1
elif ch == ")":
Parentheses_num -= 1
else:
sb = sb +(list(strs)[i])
if Parentheses_num != 0:
print('括号不匹配')
return None
return sb+')'
if __name__ == '__main__':
strs = '(1,(2,3),(4,(5,6),7))'
print(removeNestedPare(strs))def removeNestedPare(strs):
if strs == None:
return None
#用来记录不匹配的(出现的次数
Parentheses_num = 0
if list(strs)[0] != '(' or list(strs)[-1] !=')':
return None
sb = '('
for i in range(len(strs)):
ch = list(strs)[i]
if ch == "(":
Parentheses_num += 1
elif ch == ")":
Parentheses_num -= 1
else:
sb = sb +(list(strs)[i])
if Parentheses_num != 0:
print('括号不匹配')
return None
return sb+')'
if __name__ == '__main__':
strs = '(1,(2,3),(4,(5,6),7))'
print(removeNestedPare(strs))
结果:
(1,2,3,4,5,6,7)