stress test maximum pairwise product in python

Solutions on MaxInterview for stress test maximum pairwise product in python by the best coders in the world

showing results for - "stress test maximum pairwise product in python"
Luigi
07 Nov 2017
1#Uses python3
2'trying to work with stress testing'
3
4__author__ = 'InnerPeace'
5
6import random
7import argparse
8
9#naive solution
10def maxpairwiseproduct(n, a):
11    assert len(a) == n, "the length of the list is not equal to n = %r" % n
12    assert n >= 2, "'n' should be great or equal than 2"
13    result = 0
14    for i in range(0, n):
15        for j in range(i+1, n):
16            if a[i]*a[j] > result:
17                result = a[i]*a[j]
18
19    return result
20
21#faster vision of solution
22def maxpairwiseproductfast(n, a):
23    #assert(len(a) ==  n)
24    assert len(a) == n, "the length of the list is not equal to n = %r" % n
25    assert n >= 2, "'n' should be great or equal than 2"
26    #assert(n >= 2)
27    max1 = -1
28    max2 = -1
29    for i in range(0, n):
30        if max1 == -1:
31            max1 = i
32        elif a[i] >= a[max1]:
33            max2 = max1
34            max1 = i
35        elif max2 == -1 or a[max2] < a[i]:
36            max2 = i
37    return a[max1] * a[max2]
38
39
40if __name__ == '__main__':
41
42    parser = argparse.ArgumentParser()
43    parser.add_argument("-st", "-stress-test", help="run the stress testing", action="store_true")
44    args = parser.parse_args()
45    if args.st:
46        while True:
47            n = random.randint(0, 1000) + 2
48            print (n)
49            a = []
50            for i in range(0, n):
51                a.append(random.randint(0, 10000))
52            print (a)
53
54            res1 = maxpairwiseproductfast(n, a)
55            res2 = maxpairwiseproduct(n, a)
56
57            if res2 != res1:
58                print ('wrong answer: %d, %d' % (res1, res2))
59                break
60            else:
61                print ("ok")
62    else:
63        n = int(input())
64        a = [int(x) for x in input().split()]
65        print (maxpairwiseproductfast(n, a))
66        #print (maxpairwiseproduct(n, a))
67