我所拥有的是一个查找例如{[]}{([])}()
的字符串的字符串,然后我将其循环以查找它是打开还是关闭括号并将其附加到列表中。
我现在要做的是找到哪个是最深的n and并将其打印出来。所以在这个例子中我会打印中间{([
,但我很困惑如何做到这一点。我可以附加开放括号的开头然后重置它但是如何比较它们中的几个,并打印最大的那个
我的代码:
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("{(<)}")
答案 0 :(得分:2)
我不确定我是否理解你的意愿,但这会找到连续打开括号的最长序列:
In [20]: import re
In [21]: s = '{[]}{([])}()'
In [22]: max(re.findall("[\(\[\{]+",s),key=len)
Out[22]: '{(['
答案 1 :(得分:1)
您应该迭代并更新当前开放括号的数量,并保持循环时的最大值。您可以将所有左括号放在用作堆栈的字符串上,如果长度大于当前最大长度,则使用此字符串更新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)
答案 2 :(得分: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
条件轻松更改。
答案 3 :(得分: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