我正在研究以下 CSP,但在将其转换为 python 代码时遇到了困难:
问题:一个相邻有 4 个办公室的消防站需要容纳 7 名消防员,他们是:Phylis、Ann、Henry、Eva、Bill、Mark、Bob
限制条件:Mark 和 Bob 必须在同一个办公室 Henry 和 Eva 必须在同一个办公室 Ann 和 Bill 必须在同一个办公室 Ann 必须在 Phylis 或 Eva 附近的办公室
到目前为止我的代码:
import csp
from csp import Constraint, CSP
class FireOfficersContraints(Constraint[int, str]):
def __init__(self, place1: str, place2: str) -> None:
super().__init__([place1, place2])
self.place1: str = place1
self.place2: str = place2
def satisfied(self, assignment: Dict[str, str]) -> bool:
# If either place is not in the assignment, then it is not
# yet possible for their colors to be conflicting
if self.place1 not in assignment or self.place2 not in assignment:
return True
# check the color assigned to place1 is not the same as the
# color assigned to place2
return assignment[self.place1] != assignment[self.place2]
if __name__ == "__main__":
#generating a list with 4 lists for adding the fire officers
variables: List[int] = [1,2,3,4]
domains: Dict[str, List[str]] = {}
for variable in variables:
domains[variable] = ["Ann","Bill","Bob","Eva","Henry","Mark","Phylis"]
csp: CSP[str, str] = CSP(variables, domains)
#the constraints desceribe who cannot be with each other inside an office
csp.add_constraint(FireOfficersContraints("Mark", "Bob"))
csp.add_constraint(FireOfficersContraints("Henry", "Eva"))
csp.add_constraint(FireOfficersContraints("Ann", "Bill"))
solution: Optional[Dict[str, str]] = csp.backtracking_search()
if solution is None:
print("No solution found!")
else:
print(solution)
我的问题是:我需要为每个办公室制定一份清单吗?如果是这样,我将在哪里将官员添加到列表中?在满意的方法上还是在添加约束时?
非常感谢任何愿意帮助的人