Lecture "Organising information: trees", exercise 2
Opened this issue ยท 4 comments
essepuntato commented
Write the pure iterative version of the function defined in the previous exercise in Python.
RebeccaJillianBeattie commented
federicabonifazi commented
from anytree import Node
from collections import deque
a_0=Node("a")
b_0=Node("b", a_0)
c_0=Node("c", a_0)
d_0=Node("d", a_0)
e_0=Node("e", b_0)
f_0=Node("f", b_0)
g_0=Node("g", c_0)
h_0=Node("h", f_0)
i_0=Node("i", f_0)
j_0=Node("j", f_0)
test_a_0=[a_0, b_0, c_0, d_0, e_0, f_0, g_0, h_0, i_0, j_0]
a_1=Node("1")
test_a_1=[a_1]
def test_bfv(root_node, expected):
result=breadth_first_visit(root_node)
if result==expected:
return True
else:
return False
def breadth_first_visit(root_node):
output=[]
children_queue=deque()
children_queue.append(root_node)
while children_queue:
node=children_queue.popleft()
children_queue.extend(node.children)
output.append(node)
return output
print(test_bfv(a_0, test_a_0))
print(test_bfv(a_1, test_a_1))
katya-avem commented
angstigone commented