Python负数后正元素最大求和函数存在Bug,寻求修正方案
修正Python函数以正确处理负数后无正元素的情况
原函数仅累加负数之后的正元素并记录其累加和的最大值,当负数后面没有正元素时会返回0,但你的输入[1, -2]期望返回-1,这说明实际需求和最初描述的“紧随负数元素之后的正元素的最大和”存在偏差。以下提供两种针对性的修改方案:
方案1:匹配你的示例需求(负数与前面连续正元素的和的最大值)
如果你的真实需求是计算每个负数与其前面连续正元素的和的最大值,无符合条件的组合则返回0,可使用以下代码:
def some(arr): candidate_sums = [] current_positive_sum = 0 for num in arr: if num > 0: current_positive_sum += num elif num < 0: candidate_sums.append(current_positive_sum + num) current_positive_sum = 0 return max(candidate_sums) if candidate_sums else 0
测试输入[1, -2]时,函数计算1 + (-2) = -1,返回结果与你的预期一致。
方案2:匹配最初描述的需求(负数后正元素的最大累加和,无则返回最大负数)
如果你确实需要返回“紧随负数之后的正元素的最大累加和”,同时希望负数后无正元素时返回该负数本身(而非0),可使用以下代码:
def some(arr): candidate_sums = [] current_sum = 0 in_negative_sequence = False for num in arr: if num < 0: candidate_sums.append(num) current_sum = 0 in_negative_sequence = True elif in_negative_sequence and num > 0: current_sum += num candidate_sums.append(current_sum) return max(candidate_sums) if candidate_sums else 0
测试输入[1, -2]时,候选列表包含[-2],返回-2;输入[-1, 2, 3]时,候选列表包含[-1, 2, 5],返回5,符合最初的需求描述。
内容的提问来源于stack exchange,提问作者TAHER El Mehdi
相关产品推荐
相关产品推荐

