Forward-chain over the exam Q8 knowledge base: repeatedly fire any rule whose premises are all known, print each derived fact in order, and stop at the fixpoint.
Forward-chain over the exam Q8 knowledge base: repeatedly fire any rule whose premises are all known, print each derived fact in order, and stop at the fixpoint.
Answer
def forward_chain(facts, rules): kb = set(facts) changed = True while changed: changed = False for premises, conclusion in rules: if set(premises) <= kb and conclusion not in kb: kb.add(conclusion) print(f"derived: {conclusion}") changed = True print("no new facts -- fixpoint") # Exam Q8 knowledge base (definite rules). The disjunctive statement # "cat not sleeping -> absent OR present" is resolved to the productive # disjunct cat_absent so reasoning can proceed. rules = [ (["cat_not_sleeping"], "cat_absent"), # stmt 3 (resolved) (["cat_absent"], "mice_present"), # stmt 1 (["dog_present"], "cat_absent"), # stmt 2 (["dog_absent", "cat_absent"], "mice_present"), # stmt 4 ] forward_chain(["dog_absent", "cat_not_sleeping"], rules)