Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert for loop to recursion to deep copy a nested list

Need your help in converting this function to use only recursion. Currently it’s using a for loop and recursion but it needs to use only recursion.
The function gets a list or a nested list and needs to return a copied list (deep copy!).

And I can not import deepcopy from copy or use list comprehension.

def my_deepcopy(nested_list: List[Any]) -> List[Any]:
    results = []
    for item in nested_list:
        if not isinstance(item, list):
            results.append(item)
        else:
            results.append(my_deepcopy(item))
    return results

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The standard way to turn an iterative function into a recursive function is to have a base case for an empty list, and then add the recursive result from the first list item to the results for the remaining list items. E.g.:

>>> def list_deepcopy(item):
...     if not isinstance(item, list) or not item:
...         return item
...     return [list_deepcopy(item[0])] + list_deepcopy(item[1:])
...
>>> a = [1, 2, [3, 4, [5, 6]]]
>>> b = list_deepcopy(a)
>>> a[0] *= 10
>>> a[2][0] *= 10
>>> a[2][2][0] *= 10
>>> a
[10, 2, [30, 4, [50, 6]]]
>>> b
[1, 2, [3, 4, [5, 6]]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading