Open essepuntato opened 1 year ago
def test_breadth_first_visit(root_node, expected):
if expected == breadth_first_visit(root_node):
return True
else:
return False
def breadth_first_visit(root_node):
output_list = []
queue = []
queue.append(root_node)
while queue != []:
output_list.append(queue[0])
queue.extend(queue[0].children)
queue.pop(0)
return output_list
elizabeth = Node("elizabeth")
charles = Node("charles", elizabeth)
anne = Node("anne", elizabeth)
william = Node("william", charles)
harry = Node("harry", charles)
george = Node("george", william)
charlotte = Node("charlotte", william)
louis = Node("louis", william)
archie = Node("archie", harry)
royals = [elizabeth,charles,anne,william,harry,george,charlotte,louis,archie]
print(test_breadth_first_visit(elizabeth, royals))
from anytree import Node
from collections import deque
def test_breadth_first_visit(root_node, expected):
return expected == breadth_first_visit(root_node)
def breadth_first_visit(root_node):
result = list()
if root_node is None:
return
q = deque()
q.append(root_node)
while(len(q)):
node = q.popleft()
result.append(node)
for child_node in node.children:
q.append(child_node)
return result
# Tests
book = Node("book")
chapter_1 = Node("chapter1", book)
chapter_2 = Node("chapter2", book)
paragraph_1 = Node("paragraph1", chapter_1)
text_1 = Node("text1", paragraph_1)
quotation_1 = Node("quotation1", paragraph_1)
text_2 = Node("text2", quotation_1)
text_3 = Node("text3", paragraph_1)
quotation_2 = Node("quotation2", paragraph_1)
text_4 = Node("text4", quotation_2)
paragraph_2 = Node("paragraph2", chapter_1)
text_5 = Node("text5", paragraph_2)
paragraph_3 = Node("paragraph3", chapter_1)
text_6 = Node("text6", paragraph_3)
text_7 = Node("text7", chapter_2)
text_8 = Node("text8", book)
bfv = [book,
chapter_1, chapter_2, text_8,
paragraph_1, paragraph_2, paragraph_3, text_7,
text_1, quotation_1, text_3, quotation_2, text_5, text_6,
text_2, text_4]
bfv_from_chapter_1 = [chapter_1, paragraph_1, paragraph_2, paragraph_3, text_1, quotation_1, text_3, quotation_2, text_5, text_6, text_2, text_4]
print(test_breadth_first_visit(book, bfv))
print(test_breadth_first_visit(chapter_1, bfv_from_chapter_1))
Write the pure iterative version of the function defined in the previous exercise in Python.