Having two lists
A = [1, 2, 3]
B = [4, 9, 5, 3, 2, 10]
the optimal sum product can be found using:
min_sum = sum(a*b for a,b in zip(sorted(A), sorted(B)[:len(A)][::-1]))
In case A
is always given sorted, this simplified version can be used:
min_sum = sum(a*b for a,b in zip(A, sorted(B)[:len(A)][::-1]))
The important part(s) to note:
- You need factors of
A
sorted. sorted(A)
will do this job, without modifying the original A
(in contrast to A.sort()
). In case A
is already given sorted, this step can be left out.
- You need the
N
lowest values from B
, where N
is the length of A
. This can be done with sorted(B)[:len(A)]
- In order to evaluate the minimal sum of products, you need to multiply the highest number of
A
with the lowest of B
, the second hightst of A
with the second lowest of B
. That is why after getting the N
lowest values of B
the order gets reversed with [::-1]
Output
print(min_sum)
# 16
print(A)
# [1, 2, 3] <- The original list A is not modified
print(B)
# [4, 9, 5, 3, 2, 10] <- The original list B is not modified
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…