472,992 Members | 3,578 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,992 software developers and data experts.

Retrieving indexes of elements in a nested list by recursive depth

2
Hi everybody!

I am presently working on a Genetic Programming API in python.
I have a bit of a problem at the moment...
For some specific reasons, I am using nested lists data structure to represent a tree. The first element of a list is always the head of the node, while all others represent the tail of the node.
e.g. the nested list [A, [B, [D, H, I], E], [C, F, G]] represent the following tree:



I need to be able to choose at random a sub tree at a given depth, in order to swap it with another subtree coming from a different tree.
So, I really need to know the index of all subtrees at depth n.
I have come up with a small program that gives all elements in a nested list for a given depth:
Expand|Select|Wrap|Line Numbers
  1. def getChildrenNodes2(lst,depth):
  2.     result=[]
  3.     if depth>0:
  4.         for elem in getChildrenNodes2(lst,depth-1):
  5.             if isinstance(elem, list):
  6.                 result.extend(elem[1:])
  7.     else:
  8.         result =lst
  9.     return result
  10.  
But this is not the same as giving indexes of all elements at depth n...
Any idea would really be welcomed!
Cheers!
Jul 29 '07 #1
2 11140
bartonc
6,596 Expert 4TB
Hi everybody!

I am presently working on a Genetic Programming API in python.
I have a bit of a problem at the moment...
For some specific reasons, I am using nested lists data structure to represent a tree. The first element of a list is always the head of the node, while all others represent the tail of the node.
e.g. the nested list [A, [B, [D, H, I], E], [C, F, G]] represent the following tree:



I need to be able to choose at random a sub tree at a given depth, in order to swap it with another subtree coming from a different tree.
So, I really need to know the index of all subtrees at depth n.
I have come up with a small program that gives all elements in a nested list for a given depth:
Expand|Select|Wrap|Line Numbers
  1. def getChildrenNodes2(lst,depth):
  2.     result=[]
  3.     if depth>0:
  4.         for elem in getChildrenNodes2(lst,depth-1):
  5.             if isinstance(elem, list):
  6.                 result.extend(elem[1:])
  7.     else:
  8.         result =lst
  9.     return result
  10.  
But this is not the same as giving indexes of all elements at depth n...
Any idea would really be welcomed!
Cheers!
It's interesting that your list structure doesn't accurately represent your tree, as it is shown.

An index can be retrieved:
Expand|Select|Wrap|Line Numbers
  1. >>> A, B, D, H, I, E, C, F, G = range(9)
  2. >>> tree = [A, [B, [D, H, I], E], [C, F, G]]
  3. >>> tree.index([B, [D, H, I], E])
  4. 1
  5. >>> tree[1].index([D, H, I])
  6. 1
  7. >>> 
Jul 29 '07 #2
Gentr1
2
The problem was actually to find the "path" of indexes until a certain depth.
Luckily, some guru from python-forum.org (named Bill) came up with the following solution (I just added the depth stopping condition to his code).
Expand|Select|Wrap|Line Numbers
  1. def bill_subtree_indices( tree_rep ,depth):
  2.     q = [ ([],tree_rep) ]
  3.     list_of_index_lists = []
  4.     while q != []:  
  5.         (indices, sub_tree) = q.pop(0)
  6.         list_of_index_lists.append(indices)
  7.         if len(indices)==depth+1:
  8.             list_of_index_lists.pop()
  9.             return list_of_index_lists
  10.         for (ordinal, sst) in enumerate( sub_tree[1:] ):
  11.             if isinstance( sst, list ):
  12.                 idxs = indices[:]
  13.                 idxs.append(ordinal+1)
  14.                 q.append( (idxs, sst) )
  15.     return list_of_index_lists
  16.  
It gives the following results:
Expand|Select|Wrap|Line Numbers
  1. >>> bill_subtree_indices([1,[2,[3,4,[5,6,7]]],[8,[9,10,11]],[12,[13,[14,[15,16]]]]],3)
  2. [[], [1], [2], [3], [1, 1], [2, 1], [3, 1], [1, 1, 2], [3, 1, 1]]
  3. >>> bill_subtree_indices([1,[2,[3,4,[5,6,7]]],[8,[9,10,11]],[12,[13,[14,[15,16]]]]],2)
  4. [[], [1], [2], [3], [1, 1], [2, 1], [3, 1]]
  5. >>> bill_subtree_indices([1,[2,[3,4,[5,6,7]]],[8,[9,10,11]],[12,[13,[14,[15,16]]]]],1)
  6. [[], [1], [2], [3]]
  7.  
Cheers!
Jul 29 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Chris P. | last post by:
Hi. I have a very simple task to perform and I'm having a hard time doing it. Given an array called 'x' (created using the numarray library), is there a single command that rounds each of its...
2
by: Christopher | last post by:
I have a hash that is several levels deep. ie: 'vars' => { '$filers' => '10.10.10.10/32', '$networksa' => '10.10.10.10/32', '$networksb' => '10.50.0.0/16', '$wintel_boxes' =>...
2
by: rankam | last post by:
Hi There, We have a requirement for recursive elements within a XML document? Is it possible to design it through XML Schema? And what are implications using recursive elements when using DOM...
10
by: BCC | last post by:
Ive been googling and reading through my books but I haven't figured out a solution (much less an elegant one) to create a multidimensional array with a runtime determined number of dimensions. I...
14
by: BQ | last post by:
Due to a lack of resources, I have to translate the following recursive function in its iterative form. It's a kind of dichotomic search. void SearchSlaves(unsigned long start_uid, unsigned long...
12
by: coosa | last post by:
Dear all, I have table called CATEGORY, which is defined as follows: CREATE TABLE CATEGORY ( CATEGORY_ID INTEGER IDENTITY(1,1) NOT NULL, CATEGORY_NAME VARCHAR(40) NOT NULL CONSTRAINT...
9
by: Csaba Gabor | last post by:
Inside a function, I'd like to know the call stack. By this I mean that I'd like to know the function that called this one, that one's caller and so on. So I thought to do: <script...
19
by: George Sakkis | last post by:
It would be useful if list.sort() accepted two more optional parameters, start and stop, so that you can sort a slice in place. In other words, x = range(1000000) x.sort(start=3, stop=-1) ...
9
by: pereges | last post by:
Hello I need some ideas for designing a recursive function for my ray tracing program. The idea behind ray tracing is to follow the electromagnetic rays from the source, as they hit the...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.