Counting the Number of Even and Odd Elements in an Array in Python
Understanding Even and Odd Count
This task involves counting the number of even and odd elements in an array.
We will explore three different methods to achieve this in Python.
Method 1: Using Loop
This method iterates through the array and counts even and odd elements.
def count_even_odd(arr): even_count = sum(1 for num in arr if num % 2 == 0) odd_count = len(arr) - even_count print(f"Even Count: {even_count}, Odd Count: {odd_count}") arr = [1, 2, 3, 4, 5, 6, 7, 8] count_even_odd(arr)
Even Count: 4, Odd Count: 4
Method 2: Using Recursion
This method counts even and odd numbers using recursion.
def count_even_odd_rec(arr, index=0, even_count=0, odd_count=0): if index == len(arr): print(f"Even Count: {even_count}, Odd Count: {odd_count}") return if arr[index] % 2 == 0: even_count += 1 else: odd_count += 1 count_even_odd_rec(arr, index + 1, even_count, odd_count) arr = [1, 2, 3, 4, 5, 6, 7, 8] count_even_odd_rec(arr)
Even Count: 4, Odd Count: 4
Method 3: Using List Comprehension
This method uses list comprehension to determine even and odd numbers.
def count_even_odd(arr): even_count = len([num for num in arr if num % 2 == 0]) odd_count = len(arr) - even_count print(f"Even Count: {even_count}, Odd Count: {odd_count}") arr = [1, 2, 3, 4, 5, 6, 7, 8] count_even_odd(arr)
Even Count: 4, Odd Count: 4