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
CodePudding user response:
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
CodePudding user response:
This isn't quite the same as getting all of the combinations -- what you want to do is iterate over the entire first list, and for each item in the first list iterate over only the items in the second list that fall after the index of the item in the first list. In Python this would be something like:
>>> list_1 = list('abcd')
>>> list_2 = list('1234')
>>> [x y for i, x in enumerate(list_1) for y in list_2[i:]]
['a1', 'a2', 'a3', 'a4', 'b2', 'b3', 'b4', 'c3', 'c4', 'd4']