A propositional logic engine for representing and querying a knowledge base.
Sentences are built from symbols and logical connectives; the model_check
function determines whether a knowledge base entails a query by exhaustive
truth-table enumeration.
Classes
EvaluationException– Raised when a symbol is evaluated against a model that does not contain it.Sentence(abstract) – Base class for all logical sentences. Definesevaluate(model),formula(), andsymbols().Symbol(name)– A propositional variable.evaluatereturnsbool(model[name])or raisesEvaluationException.Not(operand)– Logical negation.formularenders as¬.And(*conjuncts)– Logical conjunction.add(conjunct)appends a new conjunct.formularenders operands joined by∧.Or(*disjuncts)– Logical disjunction.add(disjunct)appends a new disjunct.formularenders operands joined by∨.Implication(antecedent, consequent)– Material implication.formularenders asantecedent => consequent.Biconditional(left, right)– Logical biconditional.formularenders asleft <=> right.
Functions
model_check(knowledge, query)– ReturnsTrueifknowledgeentailsqueryunder all possible truth assignments to the symbols involved.
Install the required dependencies:
pip install -r requirements.txtWindows:
python harry.pyLinux/macOS:
python3 harry.pyfrom logic import And, Not, Or, Implication, Biconditional, Symbol, model_check
rain = Symbol("rain")
sun = Symbol("sun")
knowledge = And(
Or(rain, sun),
Implication(rain, Not(sun)),
)
print(model_check(knowledge, sun)) # True
print(model_check(knowledge, rain)) # Falsepython -m pytestRun a specific file:
python -m pytest tests/test_logic.pyRun a specific test:
python -m pytest tests/test_logic.py::test_function_nameRun tests matching a pattern:
python -m pytest -k "symbol"Run without coverage (faster):
python -m pytest --no-covpytestShort contributions are welcome and appreciated.
- Fork the repository.
- Create a branch for your change.
- Make your update and keep it focused.
- Run tests before submitting:
- Windows:
python -m pytest - Linux/macOS:
pytest
- Windows:
- Open a Pull Request with a clear description of what and why.
Please keep PRs small, readable, and related to a single improvement.