BugLab008 / 020up to 100
generatorsiteratorsgotchahard

Exhausted

The function count_positives_and_negatives(numbers) takes a list of numbers and returns a tuple (pos, neg) — the count of positive numbers and the count of negative numbers. Zeros are excluded.

For most inputs it returns the right count for positives, but the negative count always comes out as 0, no matter what's in the list.

The logic looks correct. The filter is right. The counting loops are right. So why does one of them always return zero?

hint 2after hint 1
hint 3after hint 2
solution

Read the code. Before running anything: what does the last line below give?

def count_positives_and_negatives(numbers):
"""
Returns a tuple (pos, neg) with the count of positive
and negative numbers in the list. Zeros are excluded.
Example: [1, -2, 3, -4, 0] -> (2, 2)
"""
filtered = (x for x in numbers if x != 0)
positives = sum(1 for x in filtered if x > 0)
negatives = sum(1 for x in filtered if x < 0)
return (positives, negatives)
>>> count_positives_and_negatives([1, -2, 3, -4, 0])