Implement a knowledge graph memory system:
add_entity(id, type, attributes): Store entity with metadataadd_relation(subj, pred, obj, confidence): Store triplequery(entity_id, relation_type): Get entity and its relationsfind_path(start, end, max_depth): BFS to find connection path
Entity Format:
{'type': 'Person', 'attributes': {'name': 'Alice', 'age': 30}}
Relation Format:
Tuple (subject_id, predicate, object_id, confidence)
Path Finding: Return list of predicates connecting start to end, or None if no path.
Examples
Example 1:
Input:
kg = KnowledgeGraphMemory(); kg.add_entity('a', 'Person', {'name':'Alice'}); kg.add_relation('a', 'knows', 'b', 0.9); 'knows' in [r[1] for r in kg.relations]Output:
TrueExplanation: Relation added and retrievable
Starter Code
class KnowledgeGraphMemory:
"""
Knowledge graph memory storing entities and relationships.
Enables structured reasoning over connected facts.
"""
def __init__(self):
self.entities = {} # id -> {'type': ..., 'attributes': {...}}
self.relations = [] # (subject, predicate, object, confidence)
def add_entity(self, entity_id, entity_type, attributes=None):
"""Add or update entity"""
# Your implementation here
pass
def add_relation(self, subject, predicate, object, confidence=1.0):
"""Add relationship triple"""
# Your implementation here
pass
def query(self, entity_id, relation_type=None):
"""
Query graph: get entity info and related entities.
If relation_type specified, filter by it.
Returns {'entity': ..., 'relations': [...]}
"""
# Your implementation here
pass
def find_path(self, start_id, end_id, max_depth=3):
"""Find path between two entities using BFS"""
# Your implementation here
passPython3
ReadyLines: 1Characters: 0
Ready