首页 > 解决方案 > 来自 4 个数组的最大总和组合

问题描述

我有 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)

标签: pythonarrays

解决方案


正如评论中所说,其他方法可能更有效。当然,我们需要将仪表数据与价格一起放在列表中:

A = [(1, 50.4), (2, 100.8), (3, 201.6), (4, 403.2), (5, 806.4), (6, 1612.8)]
B = [(1, 40.8), (2, 81.6), (3, 163.2), (4, 326.4), (5, 652.8), (6, 1305.6)]
C = [(1, 110), (2, 220), (3, 440), (4, 880), (5, 1760), (6, 3520)]
D = [(1, 64), (2, 128), (3, 256), (4, 512), (5, 1024), (6, 2048)]

然后,如果我们想保留您的方法(只允许我使用itertools.product而不是这 4 个 for 循环),可能的解决方案是:

def KMaxCombinations(A, B, C, D, N, K):
    pq = PriorityQueue()
    for p in product(A, B, C, D):
        meters, prices = list(zip(*p))
        for m in meters:
            if not (0<m<7):
                allgood = False
                break
        else:
            allgood = True
        if allgood and (sum(meters) == 12):
            a = sum(prices)
            pq.put((-a, a))

    count = 0
    while (count < K):
        print(pq.get()[1])
        count = count + 1

KMaxCombinations(A,B,C,D,N,K)
4123.2
4028.0
3960.8

推荐阅读