Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
2 one-line functions solution in Clear category for On the same path by CDG.Axel
from typing import Iterable, List, Tuple, Union
Node = Union[int, str]
Tree = Tuple[Node, List['Tree']]
def walk_tree(tree: Tree, pair: Tuple[Node, Node], path: List[Node]):
return pair[0] in path and pair[1] in path or \
tree and any(walk_tree(node, pair, path + [node[0]]) for node in tree[1])
def on_same_path(tree: Tree, pairs: List[Tuple[Node, Node]]) -> Iterable[bool]:
"""For each given pair of tree's nodes, say if there are on a same path."""
return [walk_tree(tree, pair, [tree[0]]) for pair in pairs]
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.')
Sept. 20, 2021