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

Generate All Replacements for List of Lists

I’m building an application in Python where I need to define the following sort of function:

generate_replacements(['a', 'b', ['c', ['e', 'f']]], 1)

The expected output is all possible versions of the input list where just one element has been replaced

[
[1, 'b', ['c', ['e', 'f']]],
['a', 1, ['c', ['e', 'f']]],
['a', 'b', 1],
['a', 'b', [1, ['e', 'f']]],
['a', 'b', ['c', 1]],
['a', 'b', ['c', [1, 'f']]],
['a', 'b', ['c', ['e', 1]]]
]

I can see that recursion is the way to go, but I’m really stuck figuring out how to even best start this.

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 :

You can generate the replacements from the list, then if you notice you are replacing a list, also pass that list back through the function recursively. This is made a bit simpler if you use a generator:

def generate_replacements(l, rep):
    for i in range(len(l)):
        yield l[0:i] + [rep] + l[i+1: ]
        if isinstance(l[i], list):
            yield from (l[0:i] + [rec] + l[i+1: ] 
                        for rec in generate_replacements(l[i], rep))


list(generate_replacements(['a', 'b', ['c', ['e', 'f']]], 1))

This give:

[[1, 'b', ['c', ['e', 'f']]],
 ['a', 1, ['c', ['e', 'f']]],
 ['a', 'b', 1],
 ['a', 'b', [1, ['e', 'f']]],
 ['a', 'b', ['c', 1]],
 ['a', 'b', ['c', [1, 'f']]],
 ['a', 'b', ['c', ['e', 1]]]]
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