Quiero hacer una copia de la lista en la función de recursión
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
3 respuestas
Una solución es envolverlo en una función de inicializador, luego llamar a esa función de inicializador en su lugar:
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[:])
Una manera de hacer esto es mantener su función original rec
, pero agregar una nueva función que rec redefine a sí misma como. Entonces, cualquier declaración que se encuentre en rec
se ejecutará exactamente una vez.
def rec(I: List[int]) -> List[int]:
new_lst = I[:] # only happens on the first call
rec = _rec # redefine the rec function so the next time it gets called, we call _rec
def _rec(I: List[int]) -> List[int]:
# ....(new_lst is edited)
rec(new_lst)
return new_lst
Podemos agregar un parámetro más.
def rec(I: List[int], is_first: bool) -> List[int]:
if is_first:
new_lst = I[:]
# edit new list
# then
rec(new_lst, False)
return new_lst
# call function
rec(some_list, True)
Preguntas relacionadas
Nuevas preguntas
python
Python es un lenguaje de programación multipropósito, de tipificación dinámica y de múltiples paradigmas. Está diseñado para ser rápido de aprender, comprender y usar, y hacer cumplir una sintaxis limpia y uniforme. Tenga en cuenta que Python 2 está oficialmente fuera de soporte a partir del 01-01-2020. Aún así, para preguntas de Python específicas de la versión, agregue la etiqueta [python-2.7] o [python-3.x]. Cuando utilice una variante de Python (por ejemplo, Jython, PyPy) o una biblioteca (por ejemplo, Pandas y NumPy), inclúyala en las etiquetas.