5 回答

TA貢獻1862條經(jīng)驗 獲得超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]]
如果您只想要特定索引的匹配括號,則可以對上述函數(shù)進行此修改:
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條經(jīng)驗 獲得超6個贊
堆棧是解決問題最簡單的方法。下面的解決方案將為您提供每對大括號的開始和結(jié)束索引作為元組列表。
在 [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條經(jīng)驗 獲得超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)
我沒有嘗試代碼,但我認(rèn)為它會起作用。

TA貢獻1797條經(jīng)驗 獲得超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_)
添加回答
舉報