查找匹配的括号,Python

时间:2017-01-14 15:26:45

标签: python list

问题:

我正在尝试编写一些python代码,用于搜索列表并返回匹配括号的索引。例如:

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

我的虚弱尝试:

我尝试循环遍历列表并找到最近的括号,但后来我意识到当你在循环中循环(loopception)时它没有用。我还尝试添加一个计数器,如果它是一个新的括号(,则会向计数器添加一个计数器,如果它是一个紧密的),则会选择一个,然后检查它是否等于-1,但这不起作用。

上一个代码:

while True:
            if(count == -1):
                iterator = j+1
                break
            else:
                j += 1
                print j
                if(commands[j] == "("):
                    count += 1
                if(commands[j] == ")"):
                    count -= 1

其中迭代器是输入,命令是数组

2 个答案:

答案 0 :(得分:1)

假设数组保持正确的打开/关闭支持序列:

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)

打印:

ERROR: Not a bracket (foo).
0 --> 2
ERROR: Not a bracket (bar).
5 --> 6
3 --> 7

答案 1 :(得分:0)

使用计数器变量,你走在正确的轨道上,但是如果没有看到整个代码,很难说到底出了什么问题。基本上,您需要做的是:确定要去哪个方向以及注意什么。初始化匹配的parens的数量,找到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]