Propositional logic and entailment by model checking
A knowledge-based agent stores what it knows as sentences in a formal language and uses inference to derive new sentences. Propositional logic is the simplest such language. Its sentences are built from proposition symbols, such as rain and wet, with the connectives not, and, or, implies, and if and only if. The meaning of a sentence is given by its truth value in each model, where a model assigns true or false to every symbol.
Python
from itertools import product
def implies(a, b):
return (not a) or b
def models_of(symbols, formula):
assignments = (dict(zip(symbols, values)) for values in product([False, True], repeat=len(symbols)))
return [model for model in assignments if formula(model)]
def entails(symbols, kb, query):
return all(query(model) for model in models_of(symbols, kb))
symbols = ["rain", "wet", "cold"]
kb = lambda m: implies(m["rain"], m["wet"]) and m["rain"]
print(len(models_of(symbols, kb)))
print(entails(symbols, kb, lambda m: m["wet"]))
print(entails(symbols, kb, lambda m: m["cold"]))
print(entails(symbols, lambda m: False, lambda m: m["cold"]))