首页 > 其他分享 >sumOfNegatives

sumOfNegatives

时间:2023-04-25 18:58:05浏览次数:34  
标签:count arr return sum sumOfNegatives negatives positives

Count of positives / sum of negatives
Given an array of integers.

Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. 0 is neither positive nor negative.

If the input is an empty array or is null, return an empty array.
Examples
For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65].
Soultions
Mine

def count_positives_sum_negatives(arr):
    if arr == []:
        return []
    else:
        count_positives = 0
        sum_negatives = 0
        for i in arr:
            if i > 0:
                count_positives += 1
            elif i < 0:
                sum_negatives += i
        
        return [count_positives, sum_negatives]

Best

def count_positives_sum_negatives(arr):
    if not arr: return []
    pos = 0
    neg = 0
    for x in arr:
      if x > 0:
          pos += 1
      if x < 0:
          neg += x
    return [pos, neg]
def count_positives_sum_negatives(arr):
    pos = sum(1 for x in arr if x > 0)
    neg = sum(x for x in arr if x < 0)
    return [pos, neg] if len(arr) else []

标签:count,arr,return,sum,sumOfNegatives,negatives,positives
From: https://www.cnblogs.com/artwalker/p/17353529.html

相关文章