"""Three independent examples with hand-built inputs. Run with Python 3.""" # Hybrid search: merge two fixture rankings. from collections import defaultdict def fuse_ranks(keyword, semantic, k=60): scores = defaultdict(float) for ranking in (keyword, semantic): for rank, doc_id in enumerate(ranking, start=1): scores[doc_id] += 1 / (k + rank) return sorted(scores, key=lambda doc_id: (-scores[doc_id], doc_id)) keyword = ["LIVA-69", "LIVA-70"] semantic = ["LIVA-70", "property-services-guide"] print(fuse_ranks(keyword, semantic)) # Graph search: traverse relationships visible to the reader. visible_edges = [ ("place-of-supply", "general_rule", "LIVA-69"), ("LIVA-69", "subject_to", "LIVA-70"), ] def neighbors(node, relation): return [ target for source, edge, target in visible_edges if source == node and edge == relation ] for general_rule in neighbors("place-of-supply", "general_rule"): for special_rule in neighbors(general_rule, "subject_to"): print(general_rule, special_rule) # A bounded follow-up: read one additional source when needed. def collect_sources(first, read_allowed): required_id = first.get("required_provision") if required_id is None: return (first["id"],) follow_up = read_allowed(required_id) if follow_up is None: return None return first["id"], follow_up["id"] general = {"id": "LIVA-69", "required_provision": "LIVA-70"} sources = {"LIVA-70": {"id": "LIVA-70"}} print(collect_sources(general, sources.get)) print(collect_sources(general, {}.get))