-
Notifications
You must be signed in to change notification settings - Fork 0
/
pickup.py
64 lines (56 loc) · 1.66 KB
/
pickup.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
from constants import *
import copy
class SELECT():
'''Helps select next variable and next value for assignment.'''
def __init__(self):
self.__degree = {}
def nextvar(self, csp):
'''Selects next variable to assign using degree and mrv heuristics.
MRV is used as a tie breaker.'''
self.__init_degree(csp)
D = csp.get_domains()
ua = csp.get_unassigned_vars()
if len(ua) == 1:
return copy.copy(ua).pop()
degrees = self.__degree
best = {
"var": None,
"size": 10000000000, # an arbitrary large number
"degree": -1,
}
for unassigned_var in ua:
size = self.__domain_size(unassigned_var, D)
degree = degrees[unassigned_var]
is_better = False
if size < best["size"]:
is_better = True
elif size == best["size"] and degree > best["degree"]:
is_better = True
if is_better:
best = {
"var": unassigned_var,
"size": size,
"degree": degree,
}
return best["var"]
def __init_degree(self, csp):
'''Determines the degree of variables.
Selecting more constraind variables first for assignment is a natural
heuristic that helps detect failure or prune large unpromising amounts
of search tree upfront.
Upon arrival of a new CSP, only if the number of variables differ
will the degrees be reinitiated.'''
X = csp.get_variables()
if self.__degree != {} and len(self.__degree.keys()) >= len(X):
return
constraints = csp.get_constraints()
for v in csp.get_variables():
d = 0
for _vars in constraints.values():
if v in _vars:
d += 1
self.__degree[v] = d
def __domain_size(self, var, D):
if var[0] == "L":
return D[var]["max"] - D[var]["min"] + 1
return len(D[var])