嵌套字符串并打印

2024-10-02 18:19:29 发布

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

我有一个字符串,它看起来像这样{[]}{([])}(),我循环查找它是一个开括号还是一个闭括号,并将它附加到列表中。 我现在想做的是找出哪一个是最深的鼻涕然后打印出来。所以在这个例子中,我会打印中间的{([,但是我不知道怎么做。我可以附加开始的开放括号,然后重置它,但如何比较他们的夫妇,虽然,并打印最大的一个

我的代码:

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("{(<)}")

Tags: orfalseindexreturnifisstackpop
3条回答

我不确定我是否正确理解你的愿望,但这是最长的连续括号:

In [20]: import re

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

In [22]: max(re.findall("[\(\[\{]+",s),key=len)
Out[22]: '{(['

像这样的?你知道吗

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条件来轻松更改。你知道吗

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

相关问题 更多 >