Sushil Jain
Sushil Jain

Reputation: 507

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?

Upvotes: 0

Views: 2667

Answers (4)

ayorgo
ayorgo

Reputation: 3927

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.

Upvotes: 1

Olvin Roght
Olvin Roght

Reputation: 7812

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

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

Upvotes: 2

spassador
spassador

Reputation: 413

You can use numpy.

import numpy as np

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

Upvotes: 3

Netwave
Netwave

Reputation: 42786

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

Upvotes: 2

Related Questions