473,387 Members | 1,456 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 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 11207
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.