Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To ensure an action happens only once during a recursive call

I have a procedure which contains a step which involves calling the procedure recursively. I want a certain action to be not done the first time but done the other times it is called recursively.

def a(string):
    while string.startswith('/'):
        string =string[1:]
    stringa = string.split('/',1)

    if(len(stringa)>1):
        a(stringa)

Basically my string is of type /a/b/c/d. I want to have stringa as {/}{a/b/c/d} during the first time and the successive recursion as
stringa ={a}{b/c/d}
stringa ={b}{c/d}
stringa ={c}{d}

like image 584
TheFallenOne Avatar asked Jan 26 '26 17:01

TheFallenOne


1 Answers

The basic pattern is to use a flag. You can set the flag as a default parameter so you don't have to pass it when first calling the function, then the function sets (or unsets...) the flag when calling recursively.

It looks something like this:

def some_function(..., is_first=True):
    if is_first:
        # code to run the first time
    else
        # code to run the other times
    # recurse
    some_function(..., is_first=False)

I don't know exactly how to translate that to your code because it's not clear what you want to do only on the first time. Plus, you start by passing in a string, but your recursive call is passing in a list.

like image 188
Bryan Oakley Avatar answered Jan 28 '26 06:01

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!