Python Maximum Pairwise Fast Solution [dup]
我正在在线学习算法课程,并且试图计算数字列表中的最大成对乘积。此问题之前已被回答:
最大成对乘积快速解和
用于最大成对乘积的Python
通过查看这两个帖子,我能够通过任务。我希望也许有人可以帮助我找出如何更正我的解决方案。我能够进行压力测试,发现数组中的最大数字是否在起始索引中,它只会将自身相乘两次。
这是我使用作业自动平地机失败的测试用例
1 2 3 4 5 6 7 8 9 | Input: 2 100000 90000 Your output: 10000000000 Correct output: 9000000000 |
这是我的成对方法和压力测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 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("############################################# \ 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. |
当最大数字位于位置0时,您将获得max_index1和max_index2均为0。
这就是为什么您会变得如此。
在pairwise1函数中查找第二个最高的数字之前添加以下行。
1 2 3 4 | if max_index1==0: max_index2=1 else: max_index2=0 |
因此功能将类似于:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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]) |