我现在有一个递归语句的逻辑问题。我的代码如下
def find_postpep_site(string):
if(re.search('(G[RK])|(GKR)|(G$)', string)):
lastindex = (re.search('(G[RK])|(GKR)|(G$)', string)).end()
find_postpep_site(string[lastindex:10000])
else:
return lastindex
输出如下
Traceback (most recent call last):
File "cleavage_test.py", line 47, in <module>
mature = (data[find_pp_site(data):find_postpep_site(data)])
File "cleavage_test.py", line 38, in find_postpep_site
find_postpep_site(string[lastindex:10000])
File "cleavage_test.py", line 38, in find_postpep_site
find_postpep_site(string[lastindex:10000])
File "cleavage_test.py", line 41, in find_postpep_site
return(lastindex)
UnboundLocalError: local variable 'lastindex' referenced before assignment
这个问题并不复杂,但令人沮丧。我希望此方法是自包含的,不希望在程序主体中初始化和分配变量
因此,我的问题是,我如何分配lastindex一个值,而不在每次方法递归运行时重置它?例如(坏例子)
def find_postpep_site(string):
lastindex = 0
if(re.search('(G[RK])|(GKR)|(G$)', string)):
lastindex = (re.search('(G[RK])|(GKR)|(G$)', string)).end()
find_postpep_site(string[lastindex:10000])
else:
return lastindex
它将始终返回零
谢谢
如果函数体外部存在
lastindex
,则可以引用函数顶部的全局变量。lastindex必须全局存在或通过递归向下传递。还记得在递归步骤中添加return语句。见下文:可能这就是你要找的东西
从主程序调用时,lastindex是可选的,如果未提供,将假定为0。否则,递归调用时,将在函数调用中传递lastindex
然而,我想指出的是,我认为您可能在这里也遗漏了一条返回语句:
否则,在递归情况下将永远不会返回任何内容
相关问题 更多 >
编程相关推荐