返回在if-else语句中指定的递归变量,python中的逻辑问题

返回在if-else语句中指定的递归变量,python中的逻辑问题,python,recursion,logic,Python,Recursion,Logic,我现在有一个递归语句的逻辑问题。我的代码如下 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 lasti

我现在有一个递归语句的逻辑问题。我的代码如下

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
,则可以引用函数顶部的全局变量。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 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], lastindex)
    else:
        return lastindex
从主程序调用时,lastindex是可选的,如果未提供,则假定为0。否则,当递归调用它时,lastindex将在函数调用中传递

然而,我想指出的是,我认为您可能在这里也遗漏了一条返回语句:

return find_postpep_site(string[lastindex:10000], lastindex)

否则,在递归情况下将永远不会返回任何内容。

related:Sidenote:代码中没有定义任何方法。函数不是方法。回答不正确,因为它必须在两个分支中返回某些内容:是的,刚刚修复。我最初逐字复制了OP的代码正确答案,因为它必须在两个分支中都返回一些东西:递归函数eek中的全局变量
return find_postpep_site(string[lastindex:10000], lastindex)