#1
#Here is a list of edges:T = [('Bob','Eve'),('Alice','Carol'),('Eve','Frank'),('Alice','Doug'),('Frank','Ginger'), ('Eve','Howard'),('Carol','Irene'),('Frank','Jeff'),('Doug','Kathy'),('Bob','Luis'), ('Alice','Bob'),('Bob','Mabel'),('Ginger','Norm'),('Howard','Oprah'),('Carol','Peter'), ('Kathy','Queen'),('Mabel','Ursala'),('Luis','Ronald'),('Ginger','Sarah'),('Irene','Tom'), ('Jeff','Vince'),('Peter','Wanda'),('Oprah','Xanthia'),('Norm','Yaakov'),('Luis','Zandra')]Print('T has', Len (T),'edges') Vertices=set () forEdgeincht:s,t=Edge Vertices.add (s) vertices.add (t)Print('T has', Len (vertices),'vertices')
#2
So this could is a tree. Now lets compute the number of parents for each vertex. The result confirms that we indeed has a tree and that the root was Alice (right?).
NP = {} for in vertices: = 0 for in T: + = 1print (NP)
Yes.
We now construct a dictionary of Pairs (p,c) where p is the parent of the list of children C
#3
Adjacency_map = {} forVinchVertices:adjacency_map[v]= [] forPcinchT:adjacency_map[p].append (c)Print("node and children:") forPinchAdjacency_map:Print(P,":", Adjacency_map[p])Print ()Print(Adjacency_map)
Print (5*"hello! ")
#4
Doing DFS, which is equivalent to a tree's pre-order traversal, is quite concise in Python writing. DFS is a node that encounters deeper depths to execute immediately, rather than dragging along like BFS, joining the queue until it is impossible to traverse the same layer to select depth (sequence traversal).
# a recursive depth-first traversal of a tree defined by an Adjacency_map def Print_tree_depth_first (parent, Adjacency_map, level=0): print (level*' ', parent) = Adjacency_map[parent] for in Children: Print_tree_depth_first ( Child, Adjacency_map,level +1'Alice'print_tree_depth_ First (root, Adjacency_map)
BFS
fromCollectionsImportdeque#Breadth-first traversal using a queuedefPrint_tree_breath_first (Root, Adjacency_map): Q=deque () q.append (root) whileLen (Q) >0:p=Q.popleft ()Print(p) Children=Adjacency_map[p] forChildinchchildren:q.append (Child) Print_tree_breath_first ("Alice", Adjacency_map)
Change to the following print format:
1:alice
2:carol Doug Bob.
3: ...
Python---BFS