5.Write a program to implement Forward 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 forward_chaining(knowledge_base, query):
inferred = set()
agenda = [query]
while agenda:
fact = agenda.pop(0)
if fact not in inferred:
inferred.add(fact) # Add fact to inferred set
# Find rules whose premises are satisfied by inferred facts
matching_rules = [rule for rule in knowledge_base if all(premise in inferred for premise in rule.premises)]
for rule in matching_rules:
agenda.append(rule.conclusion)
return inferred
# Test forward chaining
print("Forward Chaining:")
print("Inferred facts:", forward_chaining(rules, "A"))
Output :
Forward Chaining:
Inferred facts: {'B', 'A'}