Thursday, March 27, 2008

Simple Tree : Python

I needed a simple example on using list in Python for
a Python tutorial :
This sample shows a way to diplay a hierachical list

tree=["Serveurs",
["Dakar",
["System",
"Banque",
"Reseaux",
['R1',
'R2']],
"Dublin",
"Denver",
"Douala",
["Queue"]]]

hidedNodes = []


def displayTree(tree,n=0):
ident = " "
nextitem = None
for item in tree:
if not isinstance(item,list):
try:
nextitem = tree[tree.index(item)+1]
except:
pass
if isinstance(nextitem, list):
print n*ident+"+" + item
if item in hidedNodes:
if nextitem[0] != 'x':
nextitem.insert(0,'x')
else:
try:
nextitem.remove('x')
except:
pass
else:
print n*ident+" "+ item
else:
if not nextitem[0] == 'x':
n = n + 1
displayTree(nextitem,n)
n = n -1


def hideNode(node):
hidedNodes.append(node)

def showNode(node):
hidedNodes.remove(node)

def test():
print "TEST 1 : Display all"
displayTree(tree)
print ""
print "TEST 2 : Hiding Douala,Dakar"
map(hideNode,['Dakar','Douala'])
displayTree(tree)
print ""
print "TEST 3 : Showing Dakar"
showNode('Dakar')
displayTree(tree)
print ""
print "TEST 4: Hide Reseaux"
hideNode('Reseaux')
displayTree(tree)

if __name__ == "__main__":
test()


No comments:

Post a Comment