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

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

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 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

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