backtracking search
wip
This commit is contained in:
@@ -130,11 +130,32 @@ class CSP:
|
|||||||
A solution if any exists, otherwise None
|
A solution if any exists, otherwise None
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def backtrack(assignment: dict[str, Any]):
|
return self._backtrack({})
|
||||||
# YOUR CODE HERE (and remove the assertion below)
|
|
||||||
assert False, "Not implemented"
|
|
||||||
|
|
||||||
return backtrack({})
|
def _select_unassigned_variable(self, assignment) -> str:
|
||||||
|
for v in self.variables:
|
||||||
|
if v not in assignment.keys():
|
||||||
|
return v
|
||||||
|
return "this shouldn't happen"
|
||||||
|
|
||||||
|
# TODO: may be wrong
|
||||||
|
def _order_domain_values(self, var, assignment) -> list[Any]:
|
||||||
|
"""least constrained value"""
|
||||||
|
|
||||||
|
def compare(value) -> int:
|
||||||
|
s = 0
|
||||||
|
for neighbor in [
|
||||||
|
b for (a, b) in self.binary_constraints.keys() if a == var
|
||||||
|
]:
|
||||||
|
if neighbor in assignment.keys():
|
||||||
|
continue
|
||||||
|
for neighbor_value in self.domains[neighbor]:
|
||||||
|
s += (value, neighbor_value) not in self.binary_constraints[
|
||||||
|
(var, neighbor)
|
||||||
|
]
|
||||||
|
return s
|
||||||
|
|
||||||
|
return sorted(list(self.domains[var]), key=compare)
|
||||||
|
|
||||||
|
|
||||||
def alldiff(variables: list[str]) -> list[tuple[str, str]]:
|
def alldiff(variables: list[str]) -> list[tuple[str, str]]:
|
||||||
|
|||||||
Reference in New Issue
Block a user