6.Write a program to implement Backward Chaining example
class Rule:
def __init__(self, premises, conclusion):
self.premises = premises
self.conclusion = conclusion
# Knowledge base
rules = [
Rule(["A"], "B"),
Rule(["B", "C"], "D"),
Rule(["D"], "E"),
Rule(["F"], "C")
]
def backward_chaining(knowledge_base, query):
def ask(fact):
# If fact is already inferred, return True
if fact in inferred:
return True
# Find rules whose conclusion is fact
matching_rules = [rule for rule in knowledge_base if rule.conclusion == fact]
# Try to prove premises of matching rules
for rule in matching_rules:
if all(ask(premise) for premise in rule.premises):
inferred.add(fact)
return True
return False
inferred = set()
return ask(query)
# Test backward chaining
print("\nBackward Chaining:")
print("Can prove E?", backward_chaining(rules, "E"))
Output :
Backward Chaining:
Can prove B? False