I am stuck on a small but complex problem since yesterday.
I have a (possibly infinitely) nested list:
[1,[2,[3,4]]] or [[1,2],[3,4]] and so on.
At each level, lists consist of two subscriptions, (I did not use tuples because the lists are likely to be of arbitrary length in the next step) Now I want to insert an element at every possible position in this list and return a list of lists of all possible insertion positions. So if I insert 5, my output should look like this:
[ [5,[1,[2,[3,4]]]], [1,[5,[2,[3,4]]]], [1,[2,[5,[3,4]]]], [1,[2,[[3,5],4]]], [1,[2,[3,[4,5]]]] ]
Background: I am trying to build a phylogenetic tree by adding one taxon at a time. Each taxon should be inserted in the position in which it is best suited.
Now I have:
def get_trees(nwklist,newid): if not isinstance(nwklist,list): return [newid,nwklist] else: return [newid,nwklist],[get_trees(nwklist[0],newid),nwklist[1]],[nwklist[0],get_trees(nwklist[1],newid)]
which does not produce the output that I want, but is a bit close.
([5, [1, [2, [3, 4]]]], [[5, 1], [2, [3, 4]]], [1, ([5, [2, [3, 4]]], [[5, 2], [3, 4]], [2, ([5, [3, 4]], [[5, 3], 4], [3, [5, 4]])])])
There should be a simple solution, possibly using lambda functions, but I just don't see it.
Christophe