I'm taking an algorithms course online and I am trying to calculate the maximum pairwise product in a list of numbers. This question has already been answered before:
maximum pairwise product fast solution and Python for maximum pairwise product
I was able to pass the assignment by looking at those two posts. I was hoping that maybe someone could help me figure out how to correct my solution. I was able to apply a stress test and found out if the largest number in the array is in the starting index it will just multiply itself twice.
This is the test case I failed using the assignment automatic grader
Input:
2
100000 90000
Your output:
10000000000
Correct output:
9000000000
Here is my pairwise method and stress test
from random import randint
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def pairwise1(numbers):
max_index1 = 0
max_index2 = 0
#find the highest number
for i, val in enumerate(numbers):
if int(numbers[i]) > int(numbers[max_index1]):
max_index1 = i
#find the second highest number
for j, val in enumerate(numbers):
if j != max_index1 and int(numbers[j]) > int(numbers[max_index2]):
max_index2 = j
#print(max_index1)
#print(max_index2)
return int(numbers[max_index1]) * int(numbers[max_index2])
def stressTest():
while True:
arr = []
for x in range(5):
random_num = randint(2,101)
arr.append(random_num)
print(arr)
print('####')
result1 = max_pairwise_product(arr)
result2 = pairwise1(arr)
print("Result 1 {}, Result2 {}".format(result1,result2))
if result1 != result2:
print("wrong answer: {} **** {}".format(result1, result2))
break
else:
print("############################################# \n Ok", result1, result2)
if __name__ == '__main__':
stressTest()
'''
length = input()
a = [int(x) for x in input().split()]
answer = pairwise1(a)
print(answer)
'''
Any feedback will be greatly appreciated.
Thanks.