I'm trying to join two lists and output all possible combinations of the merged list that maintains the ordering of the original two lists. For example:
list_1 = [9,8]
list_2 = [2,1]
#output
combo= [9821,9281,2981,2918,2198,9218]
where in each element in the list "combo", 2 always comes before 1 and 9 always comes before 8.
so far I've used permutations from itertools to do loop all possible permutations, but it is not fast enough.
Here's what I got:
from itertools import permutations
seq = [5, 9, 8, 2, 1]
plist = []
root = seq[0]
left = filter(lambda x: x > root, seq)
right = filter(lambda x: x < root, seq)
for pseq in permutations(seq[1:]):
pseq = (root,) + pseq
if list(filter(lambda x: x > root, pseq)) == left and list(filter(lambda x: x < root, pseq)) == right:
plist.append(pseq)
print plist
Thanks!