我有4个数组,有2列:一列测量米,另一列测量你每米得到的钱,我想从这4个数组中得到最高的总和组合,但我有2条规则:第一条规则是总和中的每个米值必须在1到6米之间,第二条规则是,结果的米值必须等于12米。我已经编写了一段代码,从一系列4个数组中获得最大和,但我不知道如何在代码中实现这2条规则。这就是我请求你帮助的原因
我的4个阵列:
1,2,3,4,5,6是仪表值 米值下面的数字是米赚的钱
A = [[1, 2, 3, 4, 5, 6],
[50.4, 100.8, 201.6, 403.2, 806.4, 1612.8]]
B = [[1, 2, 3, 4, 5, 6],
[40.8, 81.6, 163.2, 326.4, 652.8, 1305.6]]
C = [[1, 2, 3, 4, 5, 6],
[110, 220, 440, 880, 1760, 3520]]
D = [[1, 2, 3, 4, 5, 6],
[64, 128, 256, 512, 1024, 2048]]
我的代码:
import math
from queue import PriorityQueue
def KMaxCombinations(A, B, C, D, N, K):
# Max heap.
pq = PriorityQueue()
# Insert all the possible
# combinations in max heap.
for i in range(0,N):
for j in range(0,N):
for k in range(0,N):
for l in range(0,N):
a = A[i] + B[j] + C[k] + D[l]
pq.put((-a, a))
# Pop first N elements from
# max heap and display them.
count = 0
while (count < K):
print(pq.get()[1])
count = count + 1
# Driver method
A = [50.4, 100.8, 201.6, 403.2, 806.4, 1612.8]
B = [40.8, 81.6, 163.2, 326.4, 652.8, 1305.6]
C = [110, 220, 440, 880, 1760, 3520]
D = [64, 128, 256, 512, 1024, 2048]
N = len(A)
K = 3
# Function call
KMaxCombinations(A, B, C, D, N, K)
这可以用问题中没有的其他信息来解决。仪表编号只是阵列的基于一的索引。(请参见评论和备注:请将该信息编辑到问题中。不允许图片的外部链接。)
因为您不熟悉动态编程,而且这个问题适合于蛮力方法,所以我们将这样做。您只需要仪表号来检查约束,这可以从python的enumerate中获得。
https://docs.python.org/3/library/functions.html#enumerate
容器上的for循环不应该基于索引,而应该是类似“for a in a”这样的简单内容,但是既然我们也需要索引,那么就这样做吧
我们可以先检查约束,只包括优先级队列中传递的值
当你进行这种暴力强迫时,你真的想使用itertools。您使用这些for循环所做的基本上是itertools.product。
https://docs.python.org/3/library/itertools.html#itertools.product
此外,itertools并不关心您有多少不同的仪表组。使用itertools编写类似KMaxCombinations(米的集合,目标=12,K=3)的函数是很容易的(通过一些实践)
此外,您可以将诸如enumerate之类的迭代器直接链接到产品中。您还可以使用itertools.islice跳过不符合条件的候选人。这对这个问题没有帮助,但是如果12个不同,它可能足够高,你可以完全跳过前几个读数。或者如果它足够低,你可以跳过最后几个读数
正如评论中所说,其他方法可能更有效。当然,我们需要将仪表数据与价格一起放在列表中:
然后,如果我们想保留您的方法(请允许我使用
itertools.product
而不是这4个for循环),可能的解决方案是:下面是对发布代码的修改,以解决此问题
使用穷举搜索作为发布代码
变化:
代码
测试
输出
相关问题 更多 >
编程相关推荐