Combination between two lists using cartesian product with a small twist

I am trying to do an algorithm where I find all the possible combination between two lists but I am not sure how do we call this type of combination in math:

Input:
List 1 : [a,b,c,d] and List 2 : [1,2,3,4]

Desired output:
[a1, a2, a3,a4, b2, b3, b4, c3,c4, d4]

I am looking for answers in either python or c++ preferably but I am also open any other language

>Solution :

The expected output is mathematically akin to combinations with replacement, except that you’re drawing from a different pool for the second pick, so you can use itertools.combinations_with_replacement by passing the two lists zipped together and then cherry-pick the first item of the first tuple and the second item of the second tuple from the generated sequence of combinations for output:

from itertools import combinations_with_replacement

l1 = list('abcd')
l2 = list('1234')
print([a + b for (a, _), (_, b) in combinations_with_replacement(zip(l1, l2), 2)])

This outputs:

['a1', 'a2', 'a3', 'a4', 'b2', 'b3', 'b4', 'c3', 'c4', 'd4']

Demo: https://replit.com/@blhsing/DelectablePettyMolecule

Leave a Reply