0

我所拥有的是一个看起来像这样的字符串,{[]}{([])}()我循环它以查找它是左括号还是右括号并将其附加到列表中。我现在想做的是找到最深的嵌套并将其打印出来。所以在这个例子中我会打印中间{([但我很困惑如何去做。我可以附加开括号的开头然后重置它但是如何比较它们,并打印最大的一个

我的代码:

def is_nested(str):
    stack = []
    deepest =[]
    index=1
    open=0
    for c in str:
        if c == "{" or c == "(" or c == "[" or c =="<":
            stack.append(c) # this is push
            deepest.append(c)
            open +=1
            index +=1
        elif c == "}":
            x = stack.pop()
            index +=1
            if x != "{":
                index -=1
                x2=parens(x)
                return "False: expected %s at character index %d, but received } instead." %(x2,index)
        elif c == "]":
            x = stack.pop()
            index +=1
            if x != "[":
                index -=1
                x2=parens(x)
                return "False: expected %s at character index %d, but received ] instead." %(x2,index)
        elif c == ">":
            x = stack.pop()
            index +=1
            if x != "<":
                index -=1
                x2=parens(x)
                return "False: expected %s at character index %d, but received > instead." %(x2,index)
        elif c == ")":
            x = stack.pop()
            index +=1
            if x != "(":
                index -=1
                x2=parens(x)
                return "False: expected %s at character index %d, but received ) instead." %(x2,index)

    check(str)
    return True
def check(str):
    deepest =[]
    for c in str:
        if c == "{" or c == "(" or c == "[" or c =="<":
            deepest.append(c)
    print deepest


def parens(x):
    if x == "<":
        return ">"
    elif x =="(":
        return ")"
    elif x == "{":
        return "}"
    elif x == "[":
        return "]"


print is_nested("{[()}")
print is_nested("([)")
print is_nested("{[]({})}")
print is_nested("<()>")
print is_nested("{(<)}")
4

4 回答 4

2

不确定我是否正确理解了您的意愿,但这会找到最长的连续开括号序列:

In [20]: import re

In [21]: s = '{[]}{([])}()'

In [22]: max(re.findall("[\(\[\{]+",s),key=len)
Out[22]: '{(['
于 2013-01-29T21:33:20.623 回答
1

您应该迭代并更新当前的开括号数,并保持循环时的最大值。您可以将所有开括号放在用作堆栈的字符串上,如果长度大于 max 的当前长度,则使用此字符串更新 max。

OPEN = "<[({"
CLOSED = ">])}"
def is_nested(str):
    stack = []
    deepest =[]
    for c in str:
        if c in OPEN:
            stack.append(c)
            if len(stack)>len(deepest):
                deepest.append(c)
        elif c in CLOSED:
            x = stack.pop()
            if OPEN.index(x) != CLOSED.index(c):
                return "Error"
    return ''.join(deepest)
于 2013-01-29T20:57:01.860 回答
0

像这样的东西?

def is_nested(nested_str):
    opening = ['(', '{', '[', '<']
    closing = {'(':')','{':'}', '[':']', '<':'>'}
    braces = []
    depth = 0
    max_depth = 0
    max_depth_index = None
    for index, char in enumerate(nested_str):
        if char in opening:
            braces.append(char)
            depth += 1
        elif char == closing[braces[-1]]:
            braces.pop()
            depth -= 1
        else:
            raise ValueError("This is not a valid str")
        if depth > max_depth:
            max_depth = depth
            max_depth_index = index
    return max_depth, max_depth_index

这个函数接受一个只有大括号的字符串,并告诉您最深的嵌套级别,以及该级别嵌套的第一个实例的左大括号的索引。作为奖励,如果字符串格式错误,它将引发错误。

>>> is_nested('{[][]}')
(2, 1)
>>> is_nested('{[][<()()>]()}[]()')
(4, 5)
>>> is_nested('{(})')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "nesting.py", line 16, in is_nested
ValueError: This is not a valid str

我已将除大括号之外的任何字符定义为错误,但这可以通过修改else条件轻松更改。

于 2013-01-29T21:11:42.770 回答
0
def is_nested(in_str):
    stack = []
    deepest = tuple()

    open_b = ('(','[','{','<')
    close_b = (')',']','}','>')

    for i in in_str:
        print stack, i
        if i in open_b:
            stack.append(i)
            if len(stack) > len(deepest):
                deepest = tuple(stack)
        else:
            p = stack.pop()
            print p
            print open_b.index(p)
            print close_b[open_b.index(p)]
            if i != close_b[open_b.index(p)]:
                raise Exception('Wrongly nested')
    if len(stack) > 0:
        raise Exception('Wrongly nested')
    return deepest
于 2013-01-29T21:12:14.897 回答