我正试图编写一些python代码来搜索列表并返回匹配括号的索引。例如:
array = ["(","foo",")","(","bar","(",")",")"]
f(0) => 2
f(1) => ERROR: Not a bracket.
f(2) => 0
f(3) => 7
我试着在列表中循环查找最近的括号,但后来我意识到当循环中有循环时,它就不起作用了(loopception)。我还尝试过添加一个计数器,如果它是一个新的方括号(
,则向计数器添加一个;如果它是一个右括号)
,则需要一个计数器,然后检查它是否等于-1
,但这不起作用。在
先前代码:
^{pr2}$其中iterator是输入,commands是数组
假设数组包含正确的打开/关闭背景序列:
印刷品:
^{pr2}$有了counter变量,您就走上了正确的轨道,但是在没有看到整个代码的情况下,很难说到底出了什么问题。基本上,你要做的是:决定往哪个方向走,注意什么。将匹配的paren数初始化为1,然后遍历数组。如果您再次找到原始的parens,增加计数器,如果找到对应的,则减少计数器。如果计数器为零,则返回当前位置。在
你可以试试这样的方法:
相关问题 更多 >
编程相关推荐