python - Algorithm to unwrap recursive list of lists -
problem
say have list l of elements. elements can either literals (strings) and/or lists l', l'',... list l' can contain either literals and/or lists. unwrap them such list of literal combinations. combination looks easier show explain; refer following examples.
a basic example:
l = [a,[b,c],d]
solution:
s = [[a,b,d],[a,c,d]]
the solution combination of elements of l. second element list, wish create combination each element of list separately.
more advanced example:
l = [ a, [b,c], [d,[e]] ]
solution:
s = [ [a,b,d], [a,c,d], [a,b,e], [a,c,e] ]
i loop on elements each sublist create new combination. in third element (list
[d,[e]]
), second element yet list. contains 1 element e, when loop on it return 1 element.complex example:
l = [ [a,b], [ [c,d], [e,[f,g]] ] ]
solving subproblem, namely big list in second element:
s' = [ [c,e,f], [c,e,g], [d,e,f], [d,e,g] ]
the partially solved problem becomes:
l' = [ [a,b], [ [c,e,f], [c,e,g], [d,e,f], [d,e,g] ] ]
final solution becomes:
s = [ [a,c,e,f], [a,c,e,g], [a,d,e,f], [a,d,e,g], [b,c,e,f], [b,c,e,g], [b,d,e,f], [b,d,e,g] ]
s' shows main problem solving can occur @ sublevel. need recursion.
question
i have big hunch there must existing algorithm kind of problem (or library; i'm using python 3). can point in right direction me? can't seem figure out myself.
Comments
Post a Comment