Labmda. Конструкция python

arr = [0, 2, 3, 4, -6, -7, -10]

def count_positives_sum_negatives(arr):
    count_pos = 0
    count_neg = 0
    lambda for x in arr: count_pos + 1 if x >= 0 else count_neg + (-1*(x))
    return [count_pos, count_neg*-1]

Выход

Traceback (most recent call last):
  File "/workspace/default/tests.py", line 2, in <module>
    from solution import count_positives_sum_negatives
  File "/workspace/default/solution.py", line 4
    lambda (for x in arr): count_pos + 1 if x >= 0 else count_neg + (-1*(x))
           ^
SyntaxError: invalid syntax

Что делаю не так?

Мне необходимо посчитать количество положительных элементов и сумму отрицательных элементов. Я решил сделать это через итерацию внутри lambda. Перебирая элементы и добавляю нужные значения в переменные. Количество элементов не определено.


Ответы (2 шт):

Автор решения: n1tr0xs
  1. Пишем "нормальный вариант":
def count_positives_sum_negatives(arr):
    positive_count = 0
    negative_sum = 0
    for x in arr:
        if x<0:
            negative_sum += x
        elif x>0:
            positive_count += 1
    return [negative_sum, positive_count]
  1. Понимаем, что в лямбду если и получиться переписать, то выглядеть это будет очень-неочень.
  2. Но если на производительность можно забить:
negative_sum  = sum(filter(lambda x: x<0, arr))
positive_count = len(list(filter(lambda x: x>0, arr)))

Или так:

negative_sum = sum(x for x in arr if x<0)
positive_count = len([x for x in arr if x>0])

UPD: Лямба

n, p = (lambda: [sum(x for x in arr if x<0), len([x for x in arr if x>0])])()
→ Ссылка
Автор решения: Сергей Ш
arr = [0, 2, 3, 4, -6, -7, -10]

c, s = 0, 0
for i in arr:
    if i < 0:
        s += i
    else:
        c += 1
print([s, c])

dct = {"s": 0, "c": 0}
[dct.update({"s": dct["s"] + x}) if x < 0 else dct.update({"c": dct["c"] + 1}) for x in arr]
print([dct["s"], dct["c"]])
→ Ссылка