不显示输出Python约束,继续运行

问题描述 投票:0回答:1
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约束问题。情况是一样的。如果有人帮助我解决这个问题,那将会有很大的帮助。谢谢你。

python python-3.x python-constraint
1个回答
0
投票
  • 您有五个客户的变量,每个变量都有五个可能的值 位置、品牌和持续时间。有了这些,就有 N^y 每个槽的排列,当约束条件满足时,排列呈指数增长 添加了。
  • AllDifferentConstraint() 要求中的每个变量 指定列表具有唯一值。而且它可能会变得计算量很大,因为它呈指数级增长。就像每个槽有 5^4 种排列一样。

尝试下面的代码,让我知道它是否有效,否则会尝试其他方法。 我尝试了下面的代码..根据我的系统容量大约需要 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.")
© www.soinside.com 2019 - 2024. All rights reserved.