简体   繁体   中英

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 . Meanwhile, totSum starts off being 0 , which is why sum > totSum ends up never being 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM