Python Constraint

2.5.0 · active · verified Fri Apr 17

python-constraint is a module implementing support for handling Constraint Satisfaction Problems (CSPs) over finite domains. The current version, 2.5.0, offers enhanced features like efficient string-based constraints, negative value support, and performance improvements, with releases typically occurring several times a year.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple Constraint Satisfaction Problem (CSP) using the `Problem` class, add variables with their respective finite domains, and apply a string-based constraint. Finally, it shows how to retrieve and iterate through all valid solutions.

from constraint import Problem

problem = Problem()

# Add variables with finite domains
problem.addVariable('x', [1, 2, 3])
problem.addVariable('y', [1, 2, 3])

# Add a string-based constraint (preferred method since v2.1.0)
# x * 2 == y
problem.addConstraint('x * 2 == y', ('x', 'y'))

# Find and print all solutions
solutions = problem.getSolutions()

# Example of printing solutions
if solutions:
    print(f"Found {len(solutions)} solution(s):")
    for sol in solutions:
        print(sol)
else:
    print("No solutions found.")

view raw JSON →