首页 > 解决方案 > 返回在 if else 语句中分配的递归变量,python中的逻辑问题

问题描述

我目前遇到递归语句的逻辑问题。我的代码如下

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

这将始终返回零

谢谢

标签: pythonrecursionlogic

解决方案


如果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

推荐阅读