首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回在if else语句中赋值的递归变量,python中的逻辑问题

返回在if else语句中赋值的递归变量,python中的逻辑问题
EN

Stack Overflow用户
提问于 2018-07-07 02:53:59
回答 2查看 23关注 0票数 -2

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

代码语言:javascript
复制
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

输出如下所示

代码语言:javascript
复制
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赋值?例如(不好的例子)

代码语言:javascript
复制
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

,它总是返回零。

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-07 02:57:45

可能像这样的东西就是您要找的

代码语言:javascript
复制
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语句:

代码语言:javascript
复制
return find_postpep_site(string[lastindex:10000], lastindex)

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

票数 0
EN

Stack Overflow用户

发布于 2018-07-07 02:57:33

如果lastindex存在于函数体之外,则可以在函数顶部引用全局变量。lastindex要么是全局存在的,要么是通过递归传递下来的。记住在您的递归步骤中也添加一个return语句。如下所示:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51216218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档