找一个匹配的括号,Python

2024-09-30 10:43:03 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:

我正试图编写一些python代码来搜索列表并返回匹配括号的索引。例如:

array = ["(","foo",")","(","bar","(",")",")"]
f(0) => 2
f(1) => ERROR: Not a bracket.
f(2) => 0
f(3) => 7

我无力的尝试:

我试着在列表中循环查找最近的括号,但后来我意识到当循环中有循环时,它就不起作用了(loopception)。我还尝试过添加一个计数器,如果它是一个新的方括号(,则向计数器添加一个;如果它是一个右括号),则需要一个计数器,然后检查它是否等于-1,但这不起作用。在

先前代码:

^{pr2}$

其中iterator是输入,commands是数组


Tags: 代码列表foo计数器notbarerrorarray
2条回答

假设数组包含正确的打开/关闭背景序列:

array = ["(","foo",")","(","bar","(",")",")"]

bracketPositions = []
for i, item in enumerate(array):
    if i == 0 and item == ')':
        print("Non sense ! Exit")
        break

    if item == '(':
        bracketPositions.append(i)
    elif item ==')':
        if len(bracketPositions) > 0:
            openingPosition = bracketPositions.pop()
            print(openingPosition, ' >', i)
    else:
        print('ERROR: Not a bracket. Word is: %s.' % item)

印刷品:

^{pr2}$

有了counter变量,您就走上了正确的轨道,但是在没有看到整个代码的情况下,很难说到底出了什么问题。基本上,你要做的是:决定往哪个方向走,注意什么。将匹配的paren数初始化为1,然后遍历数组。如果您再次找到原始的parens,增加计数器,如果找到对应的,则减少计数器。如果计数器为零,则返回当前位置。在

你可以试试这样的方法:

def match(array, pos):
    try:
        step  = {"(": +1,  ")": -1} [array[pos]] # go left or right?
        other = {"(": ")", ")": "("}[array[pos]] # what to look for?
        count = 1   # number of 'other' we have to find
        cur   = pos # current position
        while True:
            cur += step  # go one step further
            if array[cur] == array[pos]: # nested parens
                count += 1
            if array[cur] == other: # found match (but maybe for nested)
                count -= 1
            if count == 0:  # found match for original parens
                return cur
    except KeyError:
        # not a ( or ) or no match found
        return None

array = ["(","foo",")","(","bar","(",")",")"]
print([match(array, i) for i, _ in enumerate(array)])
# [2, None, 0, 7, None, 6, 5, 3]

相关问题 更多 >

    热门问题