5 回答
TA贡献1862条经验 获得超7个赞
使用堆栈,在遍历字符串时跟踪所有对:
def find_matching_parens(s, braces=None):
openers = braces or {"(": ")"}
closers = {v: k for k, v in openers.items()}
stack = []
result = []
for i, c in enumerate(s):
if c in openers:
stack.append([c, i])
elif c in closers:
if not stack:
raise ValueError(f"tried to close brace without an open at position {i}")
pair, idx = stack.pop()
result.append([idx, i])
if pair != closers[c]:
raise ValueError(f"mismatched brace at position {i}")
if stack:
raise ValueError(f"no closing brace at position {i}")
return result
if __name__ == "__main__":
print(find_matching_parens("(foo(bar)()baz(a(fz()asdf)))"))
输出:
[[4, 8], [9, 10], [19, 20], [16, 25], [14, 26], [0, 27]]
如果您只想要特定索引的匹配括号,则可以对上述函数进行此修改:
def find_matching_paren(s, i, braces=None):
openers = braces or {"(": ")"}
closers = {v: k for k, v in openers.items()}
stack = []
result = []
if s[i] not in openers:
raise ValueError(f"char at index {i} was not an opening brace")
for ii in range(i, len(s)):
c = s[ii]
if c in openers:
stack.append([c, ii])
elif c in closers:
if not stack:
raise ValueError(f"tried to close brace without an open at position {i}")
pair, idx = stack.pop()
if pair != closers[c]:
raise ValueError(f"mismatched brace at position {i}")
if idx == i:
return ii
if stack:
raise ValueError(f"no closing brace at position {i}")
return result
if __name__ == "__main__":
print(find_matching_paren("(foo(barbaz(a(fz()asdf))))", 4)) # => 24
TA贡献1877条经验 获得超6个赞
堆栈是解决问题最简单的方法。下面的解决方案将为您提供每对大括号的开始和结束索引作为元组列表。
在 [37] 中:string = '(foo(bar))'
In [38]: braces_stack = []
...:
...: pairs = []
...:
...: for index, char in enumerate(string):
...: if char=='(':
...: braces_stack.append(index)
...: elif char==')':
...: idx = braces_stack.pop()
...: pairs.append((idx, index))
...:
...:
In [39]: pairs
Out[39]: [(4, 8), (0, 9)]
TA贡献1809条经验 获得超8个赞
indexes_of_opening_brackets = []
indexes_of_closing_brackets = []
for index, item in enumerate(string):
if item == "(":
indexes_of_opening_brackets.append(index)
elif item == ")":
indexes_of_closing_brackets.append(index)
我没有尝试代码,但我认为它会起作用。
TA贡献1797条经验 获得超4个赞
试试这个,如果我正确理解你的问题,这就是你想要的。在这里,我在字符串中搜索“(”和“)”后将值附加到字典中
string = "(foo(bar))"
print(string.find(")"))
num = string.count(")")
a = 0
b = 0
dict_ = {"open": [], "close": []}
a = string.find("(", a)
dict_["open"].append(a)
for _ in range(0, num):
a = string.find("(", a+1)
dict_["open"].append(a)
b = string.find(")", b+1)
dict_["close"].append(b)
dict_["open"].pop(-1)
print(dict_)
添加回答
举报