Search code examples
pythonalgorithmmath

All possible decision paths / outcomes given multiple choices at each decision


Given I am iterating through multiple lists of elements that are zipped together, I need to create all possible outcomes given I can only choose an element from a single list at each iteration.

Example input 1:

a = [3,19,13]
b = [20,18,7]

Example output 1:

[[3, 19, 13], [3, 19, 7], [3, 18, 13], [3, 18, 7], [20, 19, 13], [20, 19, 7], [20, 18, 13], [20, 18, 7]]

Example input 2:

a = ['A','B']
b = ['C','D']

Example output 2:

[['A', 'B'], ['A', 'D'], ['C', 'B'], ['C', 'D']]

I'm struggling to find the right mathematical terminology to define exactly what I am asking for. I do not think permutations, combinations, or cartesian product are correct or precise enough.


Solution

  • You can compute this by taking the product of the sets of the n'th terms of the list. Each set will contain all the choices for the n'th element of the new list, so the product of all the sets will be all the possible combinations of those choices.

    Implementation-wise, you can use zip to gather the "sets" into lists and itertools.product to multiply the albums setlists sets/lists.

    import itertools
    
    def get_paths(*iterables):
        return list(itertools.product(*zip(*iterables)))
    
    a = [3,19,13]
    b = [20,18,7]
    
    print(get_paths(a, b))
    
    a = ['A','B']
    b = ['C','D']
    
    print(get_paths(a, b))