比如有一個字符串s:如何在python字符串中找到相反的字符?
s = "((abc)((123))())blabla"
我們知道S的開頭「(」我們要找到它的對面,「)」「布拉布拉」之前,如何做到這一點在python中?
是否可以在不使用狀態機的情況下以簡單直觀的方式執行此操作? 還是有任何圖書館可以做到這一點?
比如有一個字符串s:如何在python字符串中找到相反的字符?
s = "((abc)((123))())blabla"
我們知道S的開頭「(」我們要找到它的對面,「)」「布拉布拉」之前,如何做到這一點在python中?
是否可以在不使用狀態機的情況下以簡單直觀的方式執行此操作? 還是有任何圖書館可以做到這一點?
您可以嘗試正則表達式,pyparsing,但線性時間複雜度幼稚的選項下面簡單的方式
>>> s = "((abc)((123))())blabla"
>>> count = 0
>>> for i,e in enumerate(s):
if e == '(':
count += 1
elif e == ')':
count -= 1
if not count:
break
>>> s[:i + 1]
'((abc)((123))())'
>>>
謝謝你,這是像我想的那麼簡單。 – zchenah
的代碼就可以實現,通過:
from collections import defaultdict
opens = defaultdict(int)
open_close_pair = []
s = '((abc)((123))())blabla'
openc, closec = '(', ')'
for c in range(0, len(s)):
if s[c] == openc:
# +1 in every entry
for key, val in opens.items():
opens[key] += 1
opens[c] += 1
elif s[c] == closec:
# -1 in every entery
for key, val in opens.items():
opens[key] -= 1
else:
pass
for key, val in opens.items():
if val == 0:
# open the entry to the open close pairs
open_close_pair.append((key, c))
# the bracket is close so can be removed from the counter
del opens[key]
for x in open_close_pair:
print " %s %s " % (s[x[0]], s[x[1]])
print open_close_pair
print opens
輸出是:
()
()
()
()
()
[(1, 5), (7, 11), (6, 12), (13, 14), (0, 15)]
defaultdict(<type 'int'>, {})
的算法是:
謝謝你我的傢伙我的答案,但我認爲它不夠簡單.. – zchenah
http://stackoverflow.com/questions/524548/regular-expression-to- detect-semi-colon-terminated-c-for-while-loops/524624#524624這可能有助於 – Amit
nope,我擔心你無法逃避這類問題的正則表達式 – EnricoGiampieri
@AmitMizrahi非常感謝你,這是一個很好的辦法。所以這個問題應該改變,是否有任何lib做這種事情.. – zchenah