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 = 3
Input : {‘x’: 4, ‘y’:9, ‘z’:16}
Output : Even = 2, odd = 1
Approach using values() Function: Traverse the dictionary and extract its elements using values() function and for each extracted value, check if it is even or odd. Finally, print the respective counts.
Python3
def countEvenOdd( dict ):
even = 0
odd = 0
for i in dict .values():
if i % 2 = = 0 :
even = even + 1
else :
odd = odd + 1
print ( "Even Count: " , even)
print ( "Odd Count: " , odd)
dict = { 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 , 'e' : 5 }
countEvenOdd( dict )
|
Output:
Even Count: 2
Odd Count: 3
Time Complexity: O(N), where N is the length of dict
Auxiliary Space: O(1)
Alternate Approach: Iterate over each item in the dictionary, and for each element, check if it is even or odd. Finally, print the respective counts.
Python3
def countEvenOdd( dict ):
even = 0
odd = 0
for i in dict :
if dict [i] % 2 = = 0 :
even = even + 1
else :
odd = odd + 1
print ( "Even count: " , even)
print ( "Odd count: " , odd)
dict = { 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 , 'e' : 5 }
countEvenOdd( dict )
|
Output:
Even count: 2
Odd count: 3
Time Complexity: O(N), where N is the length of dict
Auxiliary Space: O(1)
Approach : Using bitwise & operator
Python3
def fun1(x):
if (x& 1 ! = 0 ):
return x
dict = { 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 , 'e' : 5 }
x = list ( dict .values())
y = filter (fun1,x)
odd = len ( list (y))
even = len (x) - odd
print ( "Even count: " , even)
print ( "Odd count: " , odd)
|
Output
Even count: 2
Odd count: 3
Time Complexity: O(N), where N is the length of dict
Auxiliary Space: O(N)
Approach : Using values(),filter() and len() methods
Python3
def fun1(x):
if (x % 2 = = 0 ):
return x
dict = { 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 , 'e' : 5 }
x = list ( dict .values())
y = filter (fun1,x)
even = len ( list (y))
odd = len (x) - even
print ( "Even count: " , even)
print ( "Odd count: " , odd)
|
Output
Even count: 2
Odd count: 3
Time Complexity: O(N), where N is the length of dict
Auxiliary Space: O(N)
Last Updated :
10 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...