Reputation: 149
I'm doing a very simple hourglass sum function that adds up values in a 2d matrix in Python. While computing the sum, my printed statement gets one value, while putting it into a variable gets another value.
def hourglassSum(arr):
max_sum = 0
for row in range(1, len(arr) - 1):
for col in range(1, len(arr[row]) - 1):
print('Printed Sum', arr[row][col] + arr[row - 1][col]
+ arr[row - 1][col - 1] + arr[row - 1][col + 1] + arr[row + 1][col]
+ arr[row + 1][col - 1] + arr[row + 1][col + 1])
computed_sum = arr[row][col] + arr[row - 1][col]
+ arr[row - 1][col - 1] + arr[row - 1][col + 1] + arr[row + 1][col]
+ arr[row + 1][col - 1] + arr[row + 1][col + 1]
print('Computed Sum',computed_sum)
if computed_sum > max_sum:
max_sum = computed_sum
return max_sum
I would expect the computed_sum to be the same that gets printed out. However my output shows two completely different numbers every loop.
I'm very new to python so I'm sure I either missed a dumb little bug, or there is something I'm not understanding. Any help is appreciated!
Upvotes: 0
Views: 71
Reputation: 22152
Statements in Python usually end at a new-line. Therefore
computed_sum = arr[row][col] + arr[row - 1][col]
is evaluated completely separately from the following to statements
+ arr[row - 1][col - 1] + arr[row - 1][col + 1] + arr[row + 1][col]
+ arr[row + 1][col - 1] + arr[row + 1][col + 1]
These are two statements summing variables, but doing nothing with the result. The first +
is an unary +
operator.
With the print(
at the beginning of
print('Printed Sum', arr[row][col] + arr[row - 1][col]
the statement has to continue into the next lines, because there is still an open (
at the new-line. So the following two lines are evaluated as part of the expression. Only the )
with a following new-line ends the statement.
You can avoid this problem by putting parantheses around the whole expression:
computed_sum = (arr[row][col] + arr[row - 1][col]
+ arr[row - 1][col - 1] + arr[row - 1][col + 1] + arr[row + 1][col]
+ arr[row + 1][col - 1] + arr[row + 1][col + 1])
Or you can put \
before the problematic line breaks to instruct Python to consider the following line a continuation of the current one (basically ignoring the new-line).
Upvotes: 3