Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a statement exactly once in recursion function

Tags:

python

I want to make a copy of list in recursion function

def rec(I: List[int]) -> List[int]:
    new_lst = I[:] # <- want to do this only on first call of rec in recursive stack
    # ....(new_lst is edited)

    rec(new_lst)
    return new_lst
like image 796
no1special Avatar asked Jun 22 '26 06:06

no1special


1 Answers

One solution is to wrap it in an initializer function, then call that initializer function instead:

def rec(I: List[int]) -> List[int]:
    ....(new_lst is edited)

    rec(new_lst)
    return new_lst

def startrec(I: List[int]) -> List[int]:
    return rec(I[:])
like image 74
Ruzihm Avatar answered Jun 25 '26 06:06

Ruzihm



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!