EX4 Constraint
EX4 Constraint
EX4 Constraint
Description:
Constraint programming is an example of the declarative programming paradigm, as opposed to the
usual imperative paradigm that we use most of the time. Most programming paradigms can be
classified as a member of either the imperative or declarative paradigm group.
Imperative programming, simply put, is based on the developer describing the solution/algorithm for
achieving a goal (some kind of result). This happens by changing the program state through
assignment statements, while executing instructions step-by-step. Therefore it makes a huge
difference in what order the instructions are written.
Declarative programming does the opposite - we don't write the steps on how to achieve a goal, we
describe the goal, and the computer gives us a solution. A common example you should be familiar
with is SQL. Do you tell the computer how to give you the results you need? No, you describe what
you need - you need the values from some column, from some table, where some conditions are
met.
Procedure
Installing the python-constraint Module
In this article we'll be working with a module called python-constraint (Note: there's a module called
"constraint" for Python, that is not what we want), which aims to bring the constraint programming
idea to Python.
Example A
Find all (x,y) where x ∈ {1,2,3} and 0 <= y < 10, and x + y >= 5
If we look at this sentence, we can see several conditions (let's call them constraints) that x and y
have to meet.
For example, x is "constrained" to the values 1,2,3, y has to be less than 10 and their sum has to be
greater than or equal to 5. This is done in a few lines of code and in a few minutes using constraint
programming.
Looking at the problem above you probably thought "So what? I can do this with 2 for loops and half
a cup of coffee in Python in less than 10 minutes".
You're absolutely right, though through this example we can get an idea of what constraint
programming looks like:
Program
import constraint
problem = constraint.Problem()
solutions = problem.getSolutions()
print("Number of solutions found: {}\n".format(len(solutions)))
Output:
Number of solutions found: 7
T = 7, W = 6, O = 5, F = 1, U = 3, R = 0
T = 7, W = 3, O = 4, F = 1, U = 6, R = 8
T = 8, W = 6, O = 7, F = 1, U = 3, R = 4
T = 8, W = 4, O = 6, F = 1, U = 9, R = 2
T = 8, W = 3, O = 6, F = 1, U = 7, R = 2
T = 9, W = 2, O = 8, F = 1, U = 5, R = 6
T = 9, W = 3, O = 8, F = 1, U = 7, R = 6