【问题标题】:Finding the highest value with the given constraints在给定的约束条件下找到最大值
【发布时间】:2016-09-05 23:29:24
【问题描述】:
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

我被困在这里了。

【问题讨论】:

  • 描述不清楚,但听起来你知道你需要代码做什么,所以我不确定你的问题是什么。你能把它变得更简单,或者尝试编写一些代码来解决它,以便回答者可以识别你正在努力解决的问题吗?
  • @trentcl 我可以简化它。给我大约 15 分钟。
  • 不会zip(*(A0, A1, A2, A3, A4)) = zip(A0, A1, A2, A3, A4)
  • @PadraicCunningham 我得到了working code,但这有点像野兽,我不会将其发布为答案,因为我不想解释它。但也许它仍然可以帮助澄清问题?我很好奇你是否可以用一个很酷的 numpy 解决方案来做到这一点:-)
  • num 的每次迭代都会产生八个 t_ 值。那么t1 最终会如何包含50,100,150,200,250 呢?它中的值不会是列表或元组,只是该迭代等于 num[0]*0 + num[1]*1 + num[2]*0 的单个数字。

标签: python arrays list


【解决方案1】:

我想这可以满足您的要求 - 至少它会从与您在问题中提到的数据相似的数据中产生总和。我发现您的示例代码非常具有误导性,因为它不会产生您在下面的书面问题描述中提到的那种 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

您可以用一个(较长的)generator expression 替换其中的大部分,类似于@Stefan Pochmann 的 cmets 中的 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))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多