我现在有一个递归语句的逻辑问题。我的代码如下
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,它总是返回零。
谢谢
发布于 2018-07-07 02:57:45
可能像这样的东西就是您要找的
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], lastindex)
else:
return lastindex当从主程序调用时,lastindex是可选的,如果没有提供,将被假定为0。否则,当它被递归调用时,lastindex将在函数调用中传递。
但是,我想指出的是,我认为您可能还遗漏了一条return语句:
return find_postpep_site(string[lastindex:10000], lastindex)否则,您将永远不会在递归情况下返回任何内容。
发布于 2018-07-07 02:57:33
如果lastindex存在于函数体之外,则可以在函数顶部引用全局变量。lastindex要么是全局存在的,要么是通过递归传递下来的。记住在您的递归步骤中也添加一个return语句。如下所示:
def find_postpep_site(string):
global lastindex #added
if(re.search('(G[RK])|(GKR)|(G$)', string)):
lastindex = (re.search('(G[RK])|(GKR)|(G$)', string)).end()
return find_postpep_site(string[lastindex:10000])
else:
return lastindexhttps://stackoverflow.com/questions/51216218
复制相似问题