Python最大成对快速解决方案[dup]

时间:2019-06-19 03:07:41

标签: python algorithm

我正在在线学习算法课程,并且尝试计算数字列表中的最大成对乘积。这个问题之前已经得到解答:

maximum pairwise product fast solutionPython for maximum pairwise product

通过查看这两个帖子,我可以通过任务。我希望也许有人可以帮助我找出如何纠正我的解决方案。我能够进行压力测试,发现数组中的最大数字是否在起始索引中,它只会自身倍增两次。

这是我使用作业自动评分器失败的测试用例

Input:
2
100000 90000

Your output:
10000000000

Correct output:
9000000000

这是我的成对方法和压力测试

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.


1 个答案:

答案 0 :(得分:1)

当最大数字位于位置0时,您将获得max_index1和max_index2均为0。 这就是为什么您会变得如此。

在#wisewise1函数中查找第二大数字之前添加以下行。

if max_index1==0:
    max_index2=1
else:
    max_index2=0

因此功能将类似于:

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

    if max_index1==0:
        max_index2=1
    else:
        max_index2=0

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