samedi 18 novembre 2017

maximum pairwise product fast solution

I am trying to apply a stress test on python maximum pairwise product, fast and slow algorithm. However, The fast code appears to return a wrong result in some tests. I think the problem comes from the if condition in the fast algorithm. The condition doesn't occur in some cases, though it should be applies. I wasn't able to figure out the problem. any help?

from random import randint
from random import randrange


def max_pairwise(n,a):
  #  n = int(input())
    res = 0
 #   a = [int(x) for x in input().split()]
    assert(len(a) == n)

    for i in range(0,n):
        for j in range(i+1,n):
            if a[i]*a[j] > res:
                res = a[i]*a[j]

    return(res)


def max_pairwise_fast(n,a):
 #   n = int(input())
 #   a = [int(x) for x in input().split()]

    max_index1 = -1
    max_index2 = -1

    for i in range(0,n):
        if a[i] > a[max_index1]:
            max_index1 = i
        else:
            continue

    for j in range(0,n):
        if ((a[j] != a[max_index1]) and (a[j] > a[max_index2])):
            max_index2 = j
        else:
            continue

    res = a[max_index1]* a[max_index2]
    return(res)


#stress_test
while(1):
    n = randint(0,9) +2
    print(n,"n")
    a = []
    for i in range (n):
        a.append(randrange(9000))
    for i in range(n):
        print(a[i],'a[i]',"/n")
    if (max_pairwise(n,a) == max_pairwise_fast(n,a)):
        print(max_pairwise(n,a), max_pairwise_fast(n,a),"true")
    else:
        print(max_pairwise(n,a), max_pairwise_fast(n,a), "false")
        break

This is an example of the result:

6 n
318 a[i] /n
7554 a[i] /n
7531 a[i] /n
7362 a[i] /n
4783 a[i] /n
4897 a[i] /n
56889174 56889174 true
5 n
6879 a[i] /n
6985 a[i] /n
8561 a[i] /n
5605 a[i] /n
3077 a[i] /n
59798585 59798585 true
9 n
8285 a[i] /n
3471 a[i] /n
2280 a[i] /n
2443 a[i] /n
5437 a[i] /n
2605 a[i] /n
1254 a[i] /n
6990 a[i] /n
2943 a[i] /n
57912150 68641225 false




Aucun commentaire:

Enregistrer un commentaire