简体   繁体   中英

Summing each element of two arrays

I have two arrays and want to sum each element of both arrays and find the maximum sum. I have programmed it like this:

sum = []
for element in arrayOne:
    sum.append(max([item + element for item in arrayTwo]))
print max(sum)

is there any better way to achieve this?

You can use numpy.

import numpy as np

a = np.array(arrayOne)
b = np.array(arrayTwo)
max = max(a + b)
print(max)

Use itertools.product with max :

from itertools import product
print(max(sum(x) for x in product(arrayOne, arrayTwo)))

Or using map:

print(max(map(sum,product(arrayOne, arrayTwo))))
max_sum = max(map(sum, zip(arrayOne, arrayTwo)))

Upd. If you need max from sum of all elements in array:

max_sum = max(sum(arrayOne), sum(arrayTwo))

If arrayOne and arrayTwo are nested lists ( [[1, 2], [3, 3], [3, 5], [4, 9]] ) and you need to find element with max sum:

max_sum = max(map(sum, arrayOne + arrayTwo))

PS Next time, please, provide examples of input and output to not let us guess what do you need.

To find a maximum of all pairwise sums of elements of two arrays of lengths n and m respectively one can just

max(arrayOne) + max(arrayTwo)

which would perform at worst in O(max(n, m)) instead of O(n*m) when going over all the combinations.

However , if, for whatever reason, it is necessary to iterate over all the pairs, the solution might be

max(foo(one, two) for one in arrayOne for two in arrayTwo)

Where foo can be any function of two numeric parameters outputting a number (or an object of any class that implements ordering ).

By the way, please avoid redefining built-ins like sum in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM