NEP -AI-LAB

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6 PROGRAM 7 PROGRAM 8 PROGRAM 9 PROGRAM 10

PART B

PROGRAM B1 . . .
DOWNLOAD PDF - AI LAB MANUAL

 
    
 
 
 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