How to rearrange array using Python?

Ian Kelly ian.g.kelly at gmail.com
Tue Oct 20 15:26:11 EDT 2015


On Tue, Oct 20, 2015 at 12:57 PM, Martin Schöön <martin.schoon at gmail.com> wrote:
> It has been a while.
> I have mastered solving Kenken and Sudoku using Python-constraint.
>
> I still have no clue on how to tell the solver how to constrain
> the number of occupants in rooms: I have made up an simple example
> with nine persons and three rooms. Wishes for room mates are
> mild in the extreme so it is very easy for a human to place these
> nine persons in the three three-bed rooms such that all wishes are
> fulfilled. Python-constraint set up by me finds 27 solutions of
> which most place more than three persons in at least one room.
>
> Anyone into CSP willing to offer me a hint?

I assume that your variables are the individuals and the domains of
those variables are the rooms. Based on the python-constraint docs,
your constraint could look something like this:

from collections import Counter

ROOM_SIZE = {
    'A': 3,
    'B': 3,
    'C': 4,
    'D': 4,
    'E': 5,
}

def room_size_constraint(*v):
    counter = Counter(v.values())
    return all(count <= ROOM_SIZE[room]
            for room, count in counter.items())

problem.addConstraint(room_size_constraint)



More information about the Python-list mailing list