gpt4 book ai didi

Python 最大成对快速解 [dup]

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:06:29 31 4
gpt4 key购买 nike

我正在在线学习算法类(class),我正在尝试计算数字列表中的最大成对乘积。这个问题之前已经回答过:

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.


最佳答案

当 max number 在位置 0 时,你会得到 max_index1 和 max_index2 都为 0。这就是为什么你会变成这样。

在#find the second highest number in pairwise1 function 之前添加以下行。

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

关于Python 最大成对快速解 [dup],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659504/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com