Python Program for Frequencies of even and odd numbers in a matrix
Last Updated :
21 Apr, 2023
Given a matrix of order m*n then the task is to find the frequency of even and odd numbers in matrix Examples:
Input : m = 3, n = 3
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
Output : Frequency of odd number = 5
Frequency of even number = 4
Input : m = 3, n = 3
{ 10, 11, 12 },
{ 13, 14, 15 },
{ 16, 17, 18 }
Output : Frequency of odd number = 4
Frequency of even number = 5
Python3
MAX=100
def freq(ar, m, n):
even = 0
odd = 0
for i in range(m):
for j in range(n):
if ((ar[i][j] % 2) == 0):
even += 1
else:
odd += 1
print(" Frequency of odd number =", odd)
print(" Frequency of even number =", even)
m = 3
n = 3
array = [ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ]
freq(array, m, n)
Output:
Frequency of odd number = 5
Frequency of even number = 4
Time Complexity: O(m*n)Auxiliary Space: O(1)
Please refer complete article on Frequencies of even and odd numbers in a matrix for more details!
Method: Using bitwise & operator
Python3
MAX=100
def freq(ar, m, n):
even = 0
odd = 0
for i in range(m):
for j in range(n):
if ((ar[i][j] & 1) == 0):
even += 1
else:
odd += 1
print(" Frequency of odd number =", odd)
print(" Frequency of even number =", even)
m = 3
n = 3
array = [ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ]
freq(array, m, n)
Output
Frequency of odd number = 5
Frequency of even number = 4
Time Complexity: O(m*n)Auxiliary Space: O(1)
Approach#3: Using sum
We start by defining the input matrix. We use list comprehension to flatten the matrix into a 1D list. We then use the sum() function along with a generator expression to count the number of odd and even numbers in the flattened list. Finally, we print the frequency of odd and even numbers.
Start with a matrix of size m x n.
Flatten the matrix into a 1D list using list comprehension.
Initialize two variables, odd_freq , and even_freq , to 0.
Iterate through the flattened list and increment odd_freq by 1 if the element is odd, and increment even_freq by 1 if the element is even.
Print the frequency of odd and even numbers.
Python3
matrix = [[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]
flat_list = [num for row in matrix for num in row]
odd_freq = sum(1 for num in flat_list if num % 2 != 0)
even_freq = sum(1 for num in flat_list if num % 2 == 0)
print("Frequency of odd numbers:", odd_freq)
print("Frequency of even numbers:", even_freq)
Output
Frequency of odd numbers: 4
Frequency of even numbers: 5
Time Complexity; O(n2 ), where n is the length of one side of the matrix. This is because the program iterates over each element in the matrix once.
Space Complexity: O(n2 ), since it creates a 1D list with n^2 elements to store the flattened matrix. However, the space required for the odd_freq and even_freq variables is constant, since they only store two integers.
Like Article
Suggest improvement
Share your thoughts in the comments
Add Your Comment
Please Login to comment...