在给定的约束条件下求最大值

2024-04-25 19:59:15 发布

您现在位置:Python中文网/ 问答频道 /正文

c = [416,585,464]

A0 = [100,50,200]
A1 = [100,100,200]
A2 = [100,150,100]
A3 = [100,200,0]
A4 = [100,250,0]

b = [300,300,300,300,300]

for num in A0,A1,A2,A3,A4:
    t0 = num[0]*1 + num[1]*1 + num[2]*1
    t1 = num[0]*0 + num[1]*1 + num[2]*0
    t2 = num[0]*0 + num[1]*0 + num[2]*0
    t3 = num[0]*0 + num[1]*0 + num[2]*1
    t4 = num[0]*1 + num[1]*0 + num[2]*0
    t5 = num[0]*0 + num[1]*1 + num[2]*1
    t6 = num[0]*1 + num[1]*1 + num[2]*0
    t7 = num[0]*1 + num[1]*0 + num[2]*1

现在检查t0中的每个值与b数组中对应的每个值。如果来自t0的任何值大于300,则t0被丢弃。你知道吗

如果不是,则将每个t_值乘以每个对应的c数组值,然后确定最大值并打印它。你知道吗

例如:t150,100,150,200,250,所有这些都等于或低于300,所以我们取0*c[0] + 1*c[1] + 0*c[2],这就得到了585。但是,这不是最高值。最大值是1049,由t5获得。它有250,300,250,200,250。取0*c[0] + 1*c[1] + 1*c[2]得到1049

我被困在这里了。你知道吗


Tags: ina2fora1数组a0numa3
1条回答
网友
1楼 · 发布于 2024-04-25 19:59:15

我想这是你想要的,至少它从数据中产生的和你在问题中提到的相似的总和。我发现您的示例代码非常具有误导性,因为它没有产生您在下面的书面问题描述中提到的那种t_值。你知道吗

from itertools import compress

c = [416,585,464]

A0 = [100,50,200]
A1 = [100,100,200]
A2 = [100,150,100]
A3 = [100,200,0]
A4 = [100,250,0]

b = [300,300,300,300,300]

selectors = [(1, 1, 1), (0, 1, 0), (0, 0, 0), (0, 0, 1),
             (1, 0, 0), (0, 1, 1), (1, 1, 0), (1, 0, 1)]

nums_limits = zip((A0, A1, A2, A3, A4), b)
maximum = None
for selector in selectors:
    if all(sum(compress(nums, selector)) <= limit for nums,limit in nums_limits):
        total = sum(compress(c, selector))
        if maximum is None or total > maximum:
            maximum = total

print(maximum)  # -> 1049

您可以用一个(longish)generator expression替换其中的大部分内容,这个类似于@Stefan Pochmann的一个注释中linked code中的内容,因此它的作用完全相同:

print(max(sum(compress(c, selector)) for selector in selectors
                  if all(sum(compress(nums, selector)) <= limit
                         for nums, limit in zip((A0, A1, A2, A3, A4), b))))

相关问题 更多 >