Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Build tree solution in Clear category for On the same path by U.V
def f_nod(tree, nodes):
q = [tree]
while q:
q1 = q.pop()
nod, subtree = q1
if nod in nodes:
return nod, subtree
for subtree1 in subtree:
if subtree1:
q.append(subtree1)
return None, []
def f_nodes(tree, nodes):
n1, t1 = f_nod(tree, nodes)
if n1 is not None and t1:
nodes.remove(n1)
n2, t2 = f_nod((n1, t1), nodes)
return n2 == nodes[0]
return False
def on_same_path(tree, pairs):
ans = []
for pair in pairs:
pair = list(pair)
a = f_nodes(tree, list(pair))
ans.append(a)
return ans
if __name__ == '__main__':
example = on_same_path(
('Me', [('Daddy', [('Grandpa', []),
('Grandma', [])]),
('Mom', [('Granny', []),
('?', [])])]),
[('Grandpa', 'Me'), ('Daddy', 'Granny')],
)
print('Example: it should be [True, False].')
print(list(example))
TESTS = (
(
('Me', [('Daddy', [('Grandpa', []),
('Grandma', [])]),
('Mom', [('Granny', []),
('?', [])])]),
[('Grandpa', 'Me'), ('Daddy', 'Granny')],
[True, False],
),
(
(1, [(2, [(4, []),
(5, [(7, []),
(8, []),
(9, [])])]),
(3, [(6, [])])]),
[(1, 5), (2, 9), (2, 6)],
[True, True, False],
),
(
(0, [(1, [(2, []),
(3, [])]),
(4, [(5, []),
(6, [])]),
(7, [(8, []),
(9, [])])]),
[(4, 2), (0, 5), (2, 3), (9, 2), (6, 4), (7, 8), (8, 1)],
[False, True, False, False, True, True, False],
),
)
for test_nb, (tree, pairs, answers) in enumerate(TESTS, 1):
user_result = list(on_same_path(tree, pairs))
if user_result != answers:
print(f'You failed the test #{test_nb}.')
print(f'Your result: {user_result}')
print(f'Right result: {answers}')
break
else:
print('Well done! Click on "Check" for real tests.')
April 3, 2023
Comments: