boolean-py

5.0 · active · verified Sun Apr 05

The boolean.py library implements a boolean algebra, allowing users to define, create, and parse boolean expressions with variables and core boolean functions (AND, OR, NOT). It supports parsing expressions from strings, simplifying them, and comparing for equivalence. Additionally, it provides capabilities for creating custom boolean DSLs by extending its tokenizer and parser. The library is currently active, with its latest version being 5.0, and generally releases updates as needed for compatibility and features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a `BooleanAlgebra` instance, define symbols, parse boolean expressions from strings, and construct them directly using Python operators. It also shows how to evaluate expressions by substituting symbol values and then simplifying them.

import boolean

algebra = boolean.BooleanAlgebra()

# Define symbols
fever = algebra.Symbol('fever')
cough = algebra.Symbol('cough')
headache = algebra.Symbol('headache')

# Create expressions
expression_string = "(fever | cough) & ~headache"
parsed_expression = algebra.parse(expression_string)
print(f"Parsed expression: {parsed_expression}")

# Evaluate the expression for specific symptoms
patient_symptoms = {
    'fever': True,
    'cough': False,
    'headache': False
}

evaluated_expression = parsed_expression.subs(patient_symptoms)
simplified_result = evaluated_expression.simplify()
print(f"Evaluated result for symptoms: {simplified_result}")

# Direct Python expression construction
x, y, z = algebra.symbols('x', 'y', 'z')
expr2 = (x & y) | (~z)
print(f"Python-constructed expression: {expr2}")
print(f"Simplified expr2: {expr2.simplify()}")

view raw JSON →