The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Member-only story

How to Solve Constraint Satisfaction Problems (CSPs) Using AC-3 Algorithm in Python

4 min readJan 22, 2021

--

Photo made with Canva.

The AC-3 algorithm simplifies a constraint satisfaction problem using the constraints to prune out values from the variables domain.

In this article, we will see how the AC-3 algorithm works and the implementation in Python.

How It Works

We can represent the AC-3 algorithm in 3 steps:

  1. Get all the constraints and turn each one into two arcs. For example:
    𝐴 > 𝐡 becomes 𝐴 > 𝐡 and 𝐡 < 𝐴.
  2. Add all the arcs to a queue.
  3. Repeat until the queue is empty:
    3.1. Take the first arc (π‘₯, 𝑦), off the queue (dequeue).
    3.2. For every value in the π‘₯ domain, there must be some value of the 𝑦 domain.
    3.3. Make π‘₯ arc consistent with 𝑦. To do so, remove values from π‘₯ domain for which there is no possible corresponding value for 𝑦 domain.
    3.4. If the π‘₯ domain has changed, add all arcs of the form (π‘˜, π‘₯) to the queue (enqueue). Here π‘˜ is another variable different from 𝑦 that has a relation to π‘₯.

Example

--

--

The Startup
The Startup

Published in The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Responses (2)