-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcspProblem.py
66 lines (56 loc) · 2.39 KB
/
cspProblem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# cspProblem.py - Representations of a Constraint Satisfaction Problem
# AIFCA Python3 code Version 0.8.1 Documentation at http://aipython.org
# Artificial Intelligence: Foundations of Computational Agents
# http://artint.info
# Copyright David L Poole and Alan K Mackworth 2017.
# This work is licensed under a Creative Commons
# Attribution-NonCommercial-ShareAlike 4.0 International License.
# See: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en
class Constraint(object):
"""A Constraint consists of
* scope: a tuple of variables
* condition: a function that can applied to a tuple of values
for the variables
"""
def __init__(self, scope, condition):
self.scope = scope
self.condition = condition
def __repr__(self):
return self.condition.__name__ + str(self.scope)
def holds(self,assignment):
"""returns the value of Constraint con evaluated in assignment.
precondition: all variables are assigned in assignment
"""
return self.condition(*tuple(assignment[v] for v in self.scope))
class CSP(object):
"""A CSP consists of
* domains, a dictionary that maps each variable to its domain
* constraints, a list of constraints
* variables, a set of variables
* var_to_const, a variable to set of constraints dictionary
"""
def __init__(self,domains,constraints):
"""domains is a variable:domain dictionary
constraints is a list of constriants
"""
self.variables = set(domains)
self.domains = domains
self.constraints = constraints
self.var_to_const = {var:set() for var in self.variables}
for con in constraints:
for var in con.scope:
self.var_to_const[var].add(con)
def __str__(self):
"""string representation of CSP"""
return str(self.domains)
def __repr__(self):
"""more detailed string representation of CSP"""
return "CSP("+str(self.domains)+", "+str([str(c) for c in self.constraints])+")"
def consistent(self,assignment):
"""assignment is a variable:value dictionary
returns True if all of the constraints that can be evaluated
evaluate to True given assignment.
"""
return all(con.holds(assignment)
for con in self.constraints
if all(v in assignment for v in con.scope))