comp-think/2021-2022

Lecture "Organising information: trees", exercise 2

Opened this issue ยท 4 comments

Write the pure iterative version of the function defined in the previous exercise in Python.

Iterative tree 1
Iterative tree 2
Iterative tree diagram

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))

image

I sadly - don't know why - but mixed up the two exercises and believed that the first exercise asked for the iterative process and this one for the recursive one.

I hope now it is updated in the correct section and sorry for the mistake!

Schermata 2021-12-12 alle 19 14 54

Schermata 2021-12-12 alle 19 15 00