from constraint import *
from constraint import Problem, AllDifferentConstraint
problem = Problem()
customers = ["Freda", "Opal", "Penny", "Sarah", "Vicky"]
locations = ["Brownfield", "Durham", "Iowa Falls", "Los Altos", "Redding"]
brands = ["Dodge", "Fiat", "Hyundai", "Jeep", "Nissan"]
durations = [2, 3, 4, 5, 6]
for i in range(1, 6):
problem.addVariable(f"Customer_{i}", customers)
problem.addVariable(f"Location_{i}", locations)
problem.addVariable(f"Brand_{i}", brands)
problem.addVariable(f"Duration_{i}", durations)
for attr in ["Customer", "Location", "Brand", "Duration"]:
problem.addConstraint(AllDifferentConstraint(), [f"{attr}_{i}" for i in range(1, 6)])
problem.addConstraint(lambda c1, c2, c3, c4: len({c1, c2, c3, c4}) == 4,
["Customer_5", "Location_4", "Location_2", "Brand_2"])
problem.addConstraint(lambda brand, location: brand != "Jeep" or location != "Iowa Falls",
["Brand_3", "Location_3"])
problem.addConstraint(lambda c, d: c != "Penny" or d != 6, ["Customer_4", "Duration_4"])
solutions = problem.getSolutions()
for solution in solutions:
print(solution)
这是代码。当我尝试运行代码时,代码继续运行并且不显示任何输出或错误。我不知道为什么。
我还尝试了一些简单的Python约束问题。情况是一样的。如果有人帮助我解决这个问题,那将会有很大的帮助。谢谢你。
尝试下面的代码,让我知道它是否有效,否则会尝试其他方法。 我尝试了下面的代码..根据我的系统容量大约需要 3 小时。它起作用了。
!pip install python-constraint
from constraint import Problem, AllDifferentConstraint
problem = Problem()
customers = ["Freda", "Opal", "Penny", "Sarah", "Vicky"]
locations = ["Brownfield", "Durham", "Iowa Falls", "Los Altos", "Redding"]
brands = ["Dodge", "Fiat", "Hyundai", "Jeep", "Nissan"]
durations = [2, 3, 4, 5, 6]
for i in range(1, 6):
problem.addVariable(f"Customer_{i}", customers)
problem.addVariable(f"Location_{i}", locations)
problem.addVariable(f"Brand_{i}", brands)
problem.addVariable(f"Duration_{i}", durations)
for attr in ["Customer", "Location", "Brand", "Duration"]:
problem.addConstraint(AllDifferentConstraint(), [f"{attr}_{i}" for i in range(1, 6)])
problem.addConstraint(lambda c1, c2, c3, c4: len({c1, c2, c3, c4}) == 4,
["Customer_5", "Location_4", "Location_2", "Brand_2"])
problem.addConstraint(lambda brand, location: brand != "Jeep" or location != "Iowa Falls",
["Brand_3", "Location_3"])
problem.addConstraint(lambda c, d: c != "Penny" or d != 6, ["Customer_4", "Duration_4"])
solutions = problem.getSolutions()
if solutions:
print("Solutions found:")
for solution in solutions[:5]: # Displaying the first 5 solutions only
print(solution)
else:
print("No solutions found.")