Search code examples
pythonpython-itertools

Python module to generate all permutations of possible string replacements in a string?


template = "{{ person }} is a {{ quality }} {{ occupation }}"
replacements = {
"person":["John","Matt","Steve"],
"quality":["great","dedicated"],
"occupation":["engineer","student","athelete"]
}

Output:
John is a great engineer
Matt is a great engineer
Steve is a great engineer
John is a dedicated engineer
Matt is a dedicated engineer
Steve is a dedicated engineer
John is a great student
Matt is a great student
Steve is a great student
.............................

They can be generated by using lists of lists of replaceable elements and looping over them to generate permutations, and then joining the list elements.

list_input =     [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]]

example_permutation = ["John","is","a","great","engineer"]

Is there a python module/method which can generate similar permutations ?


Solution

  • This just cartesian product of the list

    import itertools
    
    list_input =     [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]]
    for element in itertools.product(*list_input):
        print element
    

    or you can do directly from your dict @dano(suggested)

    replacements = {
    "person":["John","Matt","Steve"],
    "quality":["great","dedicated"],
    "occupation":["engineer","student","athelete"]
    }
    
    for element in itertools.product(*replacements.values()):
        print("{} is a {} {}".format(*element))
    
    
    #output 
    
    John is a great engineer
    John is a great student
    John is a great athelete
    John is a dedicated engineer
    John is a dedicated student
    John is a dedicated athelete
    Matt is a great engineer
    Matt is a great student
    Matt is a great athelete
    Matt is a dedicated engineer
    Matt is a dedicated student
    Matt is a dedicated athelete
    Steve is a great engineer
    Steve is a great student
    Steve is a great athelete
    Steve is a dedicated engineer
    Steve is a dedicated student
    Steve is a dedicated athelete