Home > OS >  Program to find a pair with highest product from array of integers
Program to find a pair with highest product from array of integers

Time:12-31

I have written a code for this. But is there any easier method or function specifically in NumPy?

I tried this code:

ar = np.array([4, 1, 2, 3, 4, 7, 0, 8])
prod = 0
ar1 = 0
for x in ar:
  i = np.where(ar == x)[0][0]
  for y in ar:
    if y == ar[i]:
      continue
    else:
      ar1 = x * y  #storing highest product
      if ar1 > prod:
        prod = ar1
        y1 = y
        x1 = x
print([x1, y1])

CodePudding user response:

Deliberately not an efficient way to do this, but it uses Numpy:

import numpy as np

x = np.array([4, 1, 2, 3, 4, 7, 0, 8], dtype=object)
o = np.outer(x, x).flatten()
a = np.argsort(o)
print(o[a][-2:]) 
'''
[56 64]
'''

Please clarify your question if this is not what you are asking for.

CodePudding user response:

Thanks to @DaniMesejo I got the answer:

ar = np.array([4, 1, 2, 3, 4, 7, 0, 8])
ar.sort()
print(ar[-2:])
  • Related