π‘ Problem Formulation: In Python, counting positive and negative numbers within a list is a common operation. You’ll encounter this problem when analyzing datasets or numbers where the distribution between positive and negative values matters. For instance, given a list [1, -4, -2, 5, 0, -6, 8]
, we want to know the count of positive numbers (3) and the count of negative numbers (3).
Method 1: Using Loops
This conventional approach involves iterating over the list using a for-loop to count positive and negative numbers separately. Itβs straightforward and easily understandable even by beginners. This method is excellent for teaching purposes but might not be the most efficient for very large lists.
Here’s an example:
numbers = [1, -4, -2, 5, 0, -6, 8] positive_count = 0 negative_count = 0 for number in numbers: if number > 0: positive_count += 1 elif number < 0: negative_count += 1 print("Positive numbers:", positive_count) print("Negative numbers:", negative_count)
Output:
Positive numbers: 3 Negative numbers: 3
This straightforward code snippet sets up counters for positive and negative numbers and iterates through the list, updating counters based on the sign of the current number. The conditional statements distinguish between positive and negative numbers, and the final print statements display the results.
Method 2: Using list comprehensions
List comprehensions in Python offer a concise way to generate new lists or to count elements adhering to certain conditions. This method is more Pythonic and can achieve the same result with less code.
Here’s an example:
numbers = [1, -4, -2, 5, 0, -6, 8] positive_count = len([num for num in numbers if num > 0]) negative_count = len([num for num in numbers if num < 0]) print("Positive numbers:", positive_count) print("Negative numbers:", negative_count)
Output:
Positive numbers: 3 Negative numbers: 3
This more concise example leverages list comprehensions to filter only positive or negative numbers and then uses the len()
function to get the counts. It demonstrates Python’s ability to condense operations into a single line for better readability.
Method 3: Using the filter function
Python’s filter()
function is made to extract elements from a list that satisfy a certain condition. Itβs built into Python and can be used with a lambda expression to count positive and negative numbers neatly.
Here’s an example:
numbers = [1, -4, -2, 5, 0, -6, 8] positive_count = len(list(filter(lambda x: x > 0, numbers))) negative_count = len(list(filter(lambda x: x < 0, numbers))) print("Positive numbers:", positive_count) print("Negative numbers:", negative_count)
Output:
Positive numbers: 3 Negative numbers: 3
By using the filter()
function with a lambda function that checks for positive or negative status, this code effectively isolates and counts the desired numbers in a clean and functional programming style.
Method 4: Using numpy library
For numerical computation tasks, the numpy library is extensively utilized for its performance and vectorized operations. Counting positive and negative numbers using numpy is highly efficient, especially on large datasets.
Here’s an example:
import numpy as np numbers = np.array([1, -4, -2, 5, 0, -6, 8]) positive_count = np.sum(numbers > 0) negative_count = np.sum(numbers < 0) print("Positive numbers:", positive_count) print("Negative numbers:", negative_count)
Output:
Positive numbers: 3 Negative numbers: 3
This method uses numpy’s vectorized operations to efficiently calculate the count of positive and negative numbers. The comparison operators result in boolean arrays, and the np.sum()
function then counts the True
values, indicating the number of positive or negative elements.
Bonus One-Liner Method 5: Using sum with a generator expression
A generator expression with the sum()
function is a nifty one-liner that can give you counts without creating intermediate lists, as list comprehensions do. It’s memory-efficient and pythonic for those who appreciate concise code.
Here’s an example:
numbers = [1, -4, -2, 5, 0, -6, 8] positive_count = sum(1 for num in numbers if num > 0) negative_count = sum(1 for num in numbers if num < 0) print("Positive numbers:", positive_count) print("Negative numbers:", negative_count)
Output:
Positive numbers: 3 Negative numbers: 3
This compact code utilizes a generator expression within the sum()
function to iterate over the list and increment the count if the condition is met, effectively summing up the occurrences without the need for extra memory storage used by lists.
Summary/Discussion
- Method 1: For-Loop. Simple and explicit, good for beginners. Not the most efficient for very large lists.
- Method 2: List Comprehensions. Pythonic and concise. Intermediate-level readability, potentially less efficient memory usage than generator expressions.
- Method 3: Filter Function. Functional programming style, clean syntax. Can be less intuitive for those not familiar with lambda expressions.
- Method 4: Using numpy. High performance on large data. Requires learning numpy and is overkill for small lists or one-off tasks.
- Method 5: Sum with a Generator Expression. Memory-efficient one-liner. Sacrifices some readability for conciseness.