[英]Why python sum() function doesn't work in this case?
The prompt for the question is linked here: Hourglass sum in 2D array问题的提示链接在这里: Hourglass sum in 2D array
I have written 2 different codes that are supposed to output the same thing.我写了 2 个不同的代码,它们应该是 output 相同的东西。
Code1代码1
def hourglassSum(arr):
total = []
for i in range(0, 4):
for j in range(0, 4):
total.append(arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j]+ arr[i+2][j+1]+ arr[i+2][j+2])
return max(total)
Code2代码2
def hourglassSum(arr):
total = []
for i in range(0, 4):
for j in range(0, 4):
total.append(sum(arr[i][j:j+2]) + arr[i+1][j+1] + sum(arr[i+2][j:j+2]))
return max(total)
The 2nd code outputs a different value.第二个代码输出不同的值。 Can anyone tell me what went wrong?谁能告诉我出了什么问题?
You forgot to include the not-included index.您忘记包含未包含的索引。 A slice has the format of start:end
where the end
integer is not included.切片的格式为start:end
,其中不包括end
integer。 So you have to do a +1 when converting from indices to a slice.因此,从索引转换为切片时,您必须执行 +1。
def hourglassSum1(arr):
total = []
for i in range(0, 4):
for j in range(0, 4):
total.append(arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j]+ arr[i+2][j+1]+ arr[i+2][j+2])
return max(total)
def hourglassSum2(arr):
total = []
for i in range(0, 4):
for j in range(0, 4):
# Use +3
total.append(sum(arr[i][j:j+3]) + arr[i+1][j+1] + sum(arr[i+2][j:j+3]))
return max(total)
l = [[1, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]
assert hourglassSum1(l) == hourglassSum2(l)
Let arr = [[1, 2, 3]]
for this example.对于此示例,设arr = [[1, 2, 3]]
。
sum(arr[0][0:2]) = 3
because we are summing 1 and 2. sum(arr[0][0:2]) = 3
因为我们将 1 和 2 相加。
sum(arr[0][0:3]) = 6
because we are summing 1, 2 and 3. sum(arr[0][0:3]) = 6
因为我们将 1、2 和 3 相加。
So the answer to your question is that [j:j+2]
does not include j+2
.所以你的问题的答案是[j:j+2]
不包括j+2
。 You want to use [j:j+3]
你想使用[j:j+3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.