Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Count Even and Odd Numbers in a List
Next article icon

Python Program for Frequencies of even and odd numbers in a matrix

Last Updated : 21 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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




# Python Program to Find the frequency
# of even and odd numbers in a matrix
 
MAX=100
  
# Function for calculating frequency
def freq(ar, m, n):
    even = 0
    odd = 0
      
    for i in range(m):
        for j in range(n):
         
            # modulo by 2 to check
            # even and odd
            if ((ar[i][j] % 2) == 0):
                even += 1
            else:
                odd += 1
      
    # print Frequency of numbers
    print(" Frequency of odd number =", odd)
    print(" Frequency of even number =", even)
 
  
# Driver code
m = 3
n = 3   
      
array = [ [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ] ]
  
freq(array, m, n)
 
# This code is contributed
# by Anant Agarwal.
 
 

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




# Python Program to Find the frequency
# of even and odd numbers in a matrix using bitwise & operator.
 
MAX=100
  
# Function for calculating frequency
def freq(ar, m, n):
    even = 0
    odd = 0
      
    for i in range(m):
        for j in range(n):
         
            # bitwise & 1 to check
            # even and odd
            if ((ar[i][j] & 1) == 0):
                even += 1
            else:
                odd += 1
      
    # print Frequency of numbers
    print(" Frequency of odd number =", odd)
    print(" Frequency of even number =", even)
 
  
# Driver code
m = 3
n = 3   
      
array = [ [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ] ]
  
freq(array, m, n)
 
# This code is contributed
# by vinay pinjala.
 
 
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.

  1. Start with a matrix of size m x n.
  2. Flatten the matrix into a 1D list using list comprehension.
  3. Initialize two variables, odd_freq, and even_freq, to 0.
  4. 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.
  5. Print the frequency of odd and even numbers.

Python3




# Example input matrix
matrix = [[10, 11, 12],
          [13, 14, 15],
          [16, 17, 18]]
 
# Using list comprehension to flatten
# the matrix into a 1D list
flat_list = [num for row in matrix for num in row]
 
# Finding the frequencies
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)
 
# Printing the output
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.



Next Article
Python Program to Count Even and Odd Numbers in a List
author
kartik
Improve
Article Tags :
  • DSA
  • Matrix
  • Python
  • Python Programs
  • School Programming
Practice Tags :
  • Matrix
  • python

Similar Reads

  • Python Program to Count Even and Odd Numbers in a List
    In Python working with lists is a common task and one of the frequent operations is counting how many even and odd numbers are present in a given list. The collections.Counter method is the most efficient for large datasets, followed by the filter() and lambda approach for clean and compact code. Us
    4 min read
  • Python program to count Even and Odd numbers in a Dictionary
    Given a python dictionary, the task is to count even and odd numbers present in the dictionary. Examples: Input : {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e' : 5}Output : Even = 2, odd = 3Input : {'x': 4, 'y':9, 'z':16}Output : Even = 2, odd = 1 Approach using values() Function: Traverse the dictionary and
    3 min read
  • Python Program to Check if a Number is Odd or Even
    Even Numbers are exactly divisible by 2 and Odd Numbers are not exactly divisible by 2. We can use modulo operator (%) to check if the number is even or odd. For even numbers, the remainder when divided by 2 is 0, and for odd numbers, the remainder is 1. In this article, we will learn how to check i
    2 min read
  • Python Program to find Sum of Negative, Positive Even and Positive Odd numbers in a List
    Given a list. The task is to find the sum of Negative, Positive Even, and Positive Odd numbers present in the List. Examples: Input: -7 5 60 -34 1 Output: Sum of negative numbers is -41 Sum of even positive numbers is 60 Sum of odd positive numbers is 6 Input: 1 -1 50 -2 0 -3 Output: Sum of negative
    7 min read
  • Python Program for Number of elements with odd factors in given range
    Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output :
    2 min read
  • Python Program to Extract Rows of a matrix with Even frequency Elements
    Given a Matrix, the task is to write a Python program to extract all the rows which have even frequencies of elements. Examples: Input: [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2], [6, 5, 6, 5], [1, 2, 3, 4]] Output: [[4, 4, 4, 4, 2, 2], [6, 5, 6, 5]]Explanation: frequency of 4-> 4 which is even frequency
    5 min read
  • Python program to print even numbers in a list
    Getting even numbers from a list in Python allows you to filter out all numbers that are divisible by 2. For example, given the list a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you might want to extract the even numbers [2, 4, 6, 8, 10]. There are various efficient methods to extract even numbers from a li
    3 min read
  • Python Program for Counting sets of 1s and 0s in a binary matrix
    Given a n × m binary matrix, count the number of sets where a set can be formed one or more same values in a row or column. Examples: Input: 1 0 1 0 1 0 Output: 8 Explanation: There are six one-element sets (three 1s and three 0s). There are two two- element sets, the first one consists of the first
    2 min read
  • Python Program to Get Sum of cubes of alternate even numbers in an array
    Given an array, write a program to find the sum of cubes of alternative even numbers in an array. Examples: Input : arr = {1, 2, 3, 4, 5, 6}Output : Even elements in given array are2,4,6Sum of cube of alternate even numbers are 2**3+6**3 = 224Input : arr = {1,3,5,8,10,9,11,12,1,14}Output : Even elem
    5 min read
  • Python Program for Check if count of divisors is even or odd
    Write a Python program for a given number “n”, the task is to find its total number of divisors that are even or odd. Examples: Input : n = 10 Output: Even Input: n = 100Output: Odd Input: n = 125Output: Even Python Program for Check if count of divisors is even or odd using Naive Approach:A naive a
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences