Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
recursive solution in Clear category for On the same path by ssk8
from typing import Iterable, List, Tuple, Union
Node = Union[int, str]
Tree = Tuple[Node, List['Tree']]
def same_path(tree: Tree, pair: Tuple[Node, Node]) -> bool:
if tree[0] in pair:
if 'found' in pair:
return True
else:
pair = ('found', pair[pair[1]!=tree[0]])
for new_tree in tree[1]:
if same_path(new_tree, pair):
return True
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 [same_path(tree, pair) or False for pair in pairs]
Aug. 31, 2021