Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for On the same path by imloafer
from typing import Iterable, List, Tuple, Union
Node = Union[int, str]
Tree = Tuple[Node, List['Tree']]
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."""
res = []
paths = []
node, subs = tree
for sub in subs:
paths.append(([node], sub))
while paths:
path, (current, subs) = paths.pop()
if subs == []:
res.append(path + [current])
continue
else:
for sub in subs:
paths.append((path + [current], sub))
return [any([a in item and b in item for item in res]) for a, b in pairs]
if __name__ == '__main__':
on_same_path([50,[[6,[[78,[[28,[]],[42,[]],[89,[]],[61,[]],[59,[]]]],[91,[[81,[]],[70,[]],[34,[]],[7,[]],[19,[]]]],[16,[[98,[]],[41,[]],[30,[]],[90,[]],[31,[]]]],[71,[[87,[[38,[]],[14,[]]]],[65,[[24,[]],[63,[]]]]]],[2,[[51,[[47,[]]]],[68,[]],[84,[]],[64,[]],[80,[]]]]]],[54,[[27,[[40,[[17,[]],[23,[]],[37,[]]]],[88,[[60,[]],[11,[]]]]]],[62,[[12,[[86,[]]]],[67,[[46,[]]]],[69,[[66,[]],[72,[]]]]]],[39,[[25,[[73,[]],[3,[]]]],[49,[[92,[]]]],[29,[[52,[]]]]]],[4,[[76,[[15,[]]]],[85,[]],[75,[]],[55,[]],[96,[[57,[]]]]]]]],[95,[[35,[[20,[[26,[[79,[]]]],[43,[]]]],[74,[[36,[]],[9,[[94,[]]]]]],[48,[[82,[]],[99,[]],[93,[]]]],[33,[[44,[]],[21,[]]]]]],[13,[[32,[[1,[]],[45,[]],[77,[]]]],[18,[[22,[]],[56,[]]]],[5,[[0,[]],[97,[]],[83,[]]]],[10,[[8,[]],[58,[[53,[]]]]]]]]]]]],
[[96,52],[74,68],[0,51],[77,51],[3,88],[53,55],[45,85],[73,62],[44,31],[5,72]])
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.')
Nov. 1, 2022
Comments: