-2

I'm currently having a logic issue with a recursive statement. My code is as follows

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

With the output as follows

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

This issue isn't incredible complicated, however it is frustrating. I want to have this method self contained and do not want to initialize and assign a variable in the main body of the program.

So my question is thus, how can I assign lastindex a value without resetting it every time the method runs recursively? For example (bad example)

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

Which will always return zero

Thanks

Pabalo Pig
  • 31
  • 5

2 Answers2

0

If lastindex exists outside the function body, you can reference the global variable at the top of your function. It is necessary that the lastindex either exists globally or is passed down through your recursion. Remember to add a return statement in your recursive step as well. See below:

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
Easton Bornemeier
  • 1,918
  • 8
  • 22
0

Possibly something like this is what you're looking for

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

When called from the main program, lastindex is optional, and if not supplied, will be assumed to be 0. Otherwise, when it is called recursively, lastindex will be passed in the function call.

However, I want to point out that I think you might be missing a return statement as well here:

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

Otherwise you'll never return anything in the recursive case.

Dillon Davis
  • 6,679
  • 2
  • 15
  • 37