我试图在hackerrank上解决这个初学者问题(我对pyhon编码非常陌生)。当给定5个整数的列表时,此问题要求计算机找出4个整数的最小(和最大)和(每次迭代中遗漏1个数字以查找其他4个和)。我的代码符合15个测试用例中的9个的要求,而其他6个则不合格。 这是问题的链接: https://www.hackerrank.com/rest/contests/master/challenges/mini-max-sum/download_pdf?language=English
我的noob诊断技能告诉我,这是因为在这6个失败的测试中,输入的数字太大,因此结果不是他们想要的。
def p(arr,i):
return sum(arr)-arr[i]
def miniMaxSum(arr):
max=sum(arr)-arr[0]
min=sum(arr)-arr[0]
for i in [1,2,3,4]:
if p(arr,i)>max:
max=p(arr,i)
else:
min=p(arr,i)
print (str(min)+" "+str(max),end='')
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
它与[1,2,3,4,5]的输入一起使用,并给出正确的输出10和14,中间用空格隔开 但是对于输入[254961783、604179258、462517083、967304281、860273491] Hackerrank告诉我,我的代码无法产生所需的输出
答案 0 :(得分:2)
您的问题是您的数据未排序,并且两次减去了[0]索引:
[254961783, 604179258, 462517083, 967304281, 860273491] # NOT SORTED
max=sum(arr)-arr[0] # these are the same values, you subtract [0] twice min=sum(arr)-arr[0] # these are the same values, you subtract [0] twice
,然后您执行复杂的操作(逐步操作请参见this)来重新计算/修复最小/最大,这不太可行。
请勿将min
和max
用作变量名-您将隐藏内置函数:
仅获取总数并减去数据的最低/最高值:
def miniMaxSum(data):
total = sum(data) # sum all
lowest = min(data) # get min using the built in function
highest = max(data) # get max using the built in function
print(total-highest, total-lowest) # print total minus max/min , sep is " " by default
miniMaxSum( [254961783, 604179258, 462517083, 967304281, 860273491] )
打印:
2181931615 2894274113
如果您对列表(arr.sort()
进行排序,则也可以print( sum(arr[:-1]), sum(arr[1:]) )
进行操作,而无需使用对列表中的数据进行切片时内置的最小/最大值。
答案 1 :(得分:0)
除了更好的解决方案之外,还有分步分析(您可以在两者之间使用打印语句来进行分析,请参见:How to debug small programs 或执行Rubber duck debugging。
将您的代码 更改为miniMaxSum( [2,6,4,9,8] )
的最小/最大值会发生什么:
min = 2+6+4+9+8-2 = 27
max = 2+6+4+9+8-2 = 27
for i in [1,2,3,4]:
(i == 1)
if p(arr,i)>max: # ([2,6,4,9,8], 1) => (29-6) == 21 > 27: No
max=p([2,6,4,9,8], 1)
else:
min=p(arr,i) # min is set to 21
(i == 2)
if p(arr,i)>max: # ([2,6,4,9,8], 2) => (29-4) == 25 > 27: No
max=p([2,6,4,9,8], 1)
else:
min=p(arr,i) # min is set to 25
(i == 3)
if p(arr,i)>max: # ([2,6,4,9,8], 3) => (29-9) == 20 > 27: No
max=p([2,6,4,9,8], 1)
else:
min=p(arr,i) # min is set to 20
(i == 4)
if p(arr,i)>max: # ([2,6,4,9,8], 3) => (29-8) == 21 > 27: No
max=p([2,6,4,9,8], 1)
else:
min=p(arr,i) # min is set to 21 -- this is NOT the minimal sum
具有调试功能的代码:
def p(arr,i):
return sum(arr)-arr[i]
def miniMaxSum(arr):
max=sum(arr)-arr[0]
min=sum(arr)-arr[0]
print(f"CurrMin: {min} CurrMax: {max}")
for i in [1,2,3,4]:
if p(arr,i)>max:
max=p(arr,i)
else:
min=p(arr,i)
print(f"i={i} -> CurrMin: {min} CurrMax: {max}")
print (str(min)+" "+str(max),end='')
miniMaxSum( [2,6,4,9,8] )
输出:
CurrMin: 27 CurrMax: 27
i=1 -> CurrMin: 23 CurrMax: 27 # min ok
i=2 -> CurrMin: 25 CurrMax: 27 # min now higher, should not have been replaced
i=3 -> CurrMin: 20 CurrMax: 27 # min ok
i=4 -> CurrMin: 21 CurrMax: 27 # min now higher, should not have been replaced
21 27 # wrong result