[英]Why does my code give me the wrong result when adding negative numbers in Python?
def hourglassSum(arr):
totSum = 0
sum = 0
for j in range(4):
for i in range(4):
sum = arr[j][i] + arr[j][i+1] +arr[j][i+2]
print(sum)
if (sum > totSum):
totSum = sum
return totSum
the purpose of my program is to find some elements from an array and add them together. 我程序的目的是从数组中查找一些元素并将它们添加在一起。 if one sum is greater that other sum then return the maximum sum.
如果一个和大于另一个和,则返回最大和。 The code works for positive numbers.
该代码适用于正数。 But doesn't work for negative numbers.
但是不适用于负数。 can anybody help me explain why?
有人可以帮我解释原因吗?
It doesn't work because the sum of negative numbers is less than 0
. 它不起作用,因为负数之和小于
0
。 Meanwhile, totSum
starts off being 0
, which is why sum > totSum
ends up never being True
. 同时,
totSum
开始为0
,这就是为什么sum > totSum
最终永远不会为True
。
Here's one way to fix it: 这是修复它的一种方法:
import math
def hourglassSum(arr):
totSum = -math.inf
for j in range(4):
for i in range(4):
sum = arr[j][i] + arr[j][i+1] +arr[j][i+2]
if (sum > totSum):
totSum = sum
return totSum
Of course, there's always a one-liner for this sort of thing: 当然,这种事情总会有一线希望:
def hourglassSum(arr):
return max(arr, key=sum)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.