Forward-chaining engine on the Q8 cat/dog/mouse KB: fire rules to a fixpoint and print each derived fact in order.
Forward-chaining engine on the Q8 cat/dog/mouse KB: fire rules to a fixpoint and print each derived fact in order.
Answer
def forward_chain(facts, rules): known = set(facts) derived = [] changed = True while changed: changed = False for premises, conclusion in rules: if all(p in known for p in premises) and conclusion not in known: known.add(conclusion) derived.append(conclusion) changed = True return derived rules = [ (['cat_absent'], 'mouse_present'), (['dog_present'], 'cat_absent'), (['cat_not_sleeping', 'dog_absent'], 'cat_absent'), (['dog_absent', 'cat_absent'], 'mouse_present'), ] facts = {'dog_absent', 'cat_not_sleeping'} for fact in forward_chain(facts, rules): print(f"derived: {fact}") print("no new facts -- fixpoint")