Scheduling Problem
A more practical application of $python$-$constraint$ is solving $scheduling$ $problems$, such as assigning people to tasks without conflicts.
1 | from constraint import Problem |
Explanation
This $Python$ code uses the $python$-$constraint$ library to solve a scheduling problem where three people (Alice, Bob, and Charlie) need to be assigned to different time slots (Slot1, Slot2, and Slot3).
The goal is to ensure that no two people are assigned to the same time slot.
Step-by-Step Explanation:
Importing the Required Module:
1
from constraint import Problem
The
Problemclass from the $python$-$constraint$ library is used to define and solve the constraint satisfaction problem (CSP).Creating the Problem Instance:
1
problem = Problem()
A
Problemobject is instantiated, which will be used to define the variables (people and time slots) and constraints (no two people in the same slot).Defining Variables:
1
2
3people = ["Alice", "Bob", "Charlie"]
slots = ["Slot1", "Slot2", "Slot3"]
problem.addVariables(people, slots)Three variables (Alice, Bob, and Charlie) are created, representing the people who need to be assigned to time slots.
Each variable can take one of the values from theslotslist (Slot1, Slot2, Slot3).Adding Constraints:
1
2
3problem.addConstraint(lambda a, b: a != b, ("Alice", "Bob"))
problem.addConstraint(lambda a, c: a != c, ("Alice", "Charlie"))
problem.addConstraint(lambda b, c: b != c, ("Bob", "Charlie"))These constraints ensure that no two people are assigned to the same time slot:
- The first constraint ensures Alice and Bob do not share the same slot.
- The second constraint ensures Alice and Charlie do not share the same slot.
- The third constraint ensures Bob and Charlie do not share the same slot.
These constraints effectively enforce that each person must be in a unique time slot.
Solving the Problem:
1
solution = problem.getSolution()
The
getSolution()method is used to find a solution that satisfies all the constraints.
The solution is returned as a dictionary where the keys are the names of the people and the values are the assigned time slots.Printing the Solution:
1
print(solution)
The solution is printed, showing which time slot each person is assigned to.
For example, the output might be something like
{'Alice': 'Slot3', 'Bob': 'Slot2', 'Charlie': 'Slot1'}, indicating that Alice is in Slot3, Bob is in Slot2, and Charlie is in Slot1.
Summary
This code solves a simple scheduling problem using constraints to ensure that three people (Alice, Bob, and Charlie) are assigned to different time slots (Slot1, Slot2, and Slot3).
The constraints ensure that no two people share the same time slot, and the solution provides a valid assignment that meets these conditions.












