简体   繁体   English

在Python中添加负数时,为什么我的代码给我错误的结果?

[英]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.

相关问题 为什么这个Python代码给出了错误的答案? - Why does this Python code give me the wrong answer? Python:为什么我的代码一直告诉我答案是错误的,而事实并非如此? - Python: why does my code keep telling me the answer is wrong when its not? 为什么在 biopython 中使用 function 来计算蛋白质的分子量与我在 python 中的代码的结果不同 - why bulit in function in biopython to calculate molecular weight of proteins not give me the same result as my code in python 为什么 Parse_Dates 在 Python 中给我错误的结果? - Why does Parse_Dates give me the wrong results in Python? 为什么我的 Chudnovsky 算法程序给出了错误的结果? - Why does my program for the Chudnovsky algorithm give the wrong result? 为什么我的Python代码显示错误的结果? - Why is my Python code displaying the wrong result? 比较数字在 Python 中给出错误的结果 - Comparing numbers give the wrong result in Python 熊猫得到错误的结果时<adding then comparing>数字,蟒蛇 - Pandas gets wrong result when <adding then comparing> numbers, python 当我的所有语法都正确时,为什么在 python 中使用“if”会给出语法错误结果? - Why does using 'if' in python give me syntax error results when all of my syntaxes are right? 为什么 BeautifulSoup 给我错误的文字? - Why does BeautifulSoup give me the wrong text?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM