📜  Python程序可计算字典中的偶数和奇数

📅  最后修改于: 2021-04-18 02:28:36             🧑  作者: Mango

给定一个Python字典,任务si会计算字典中存在的偶数和奇数。

例子:

使用values()函数:遍历字典并使用values()函数提取其元素,对于每个提取的值,检查其是偶数还是奇数。最后,打印相应的计数。

Python3
# Python3 Program to count even and
# odd numbers present in a dictionary
  
# Function to count even and odd
# numbers present in a dictionary
def countEvenOdd(dict):
      
    # Stores count of even
    # and odd elements
    even = 0
    odd = 0
      
    # Traverse the dictionary
    for i in dict.values():
        
      if i % 2 == 0:
        even = even + 1
      else:
        odd = odd + 1
          
    print("Even Count: ", even)
    print("Odd Count: ", odd)
  
# Driver Code
  
dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
countEvenOdd(dict)


Python3
# Python3 Program to count even
# and odd elements in a dictionary
  
# Function to count even and
# odd elements in a dictionary
def countEvenOdd(dict):
  even = 0
  odd = 0
    
  # Iterate over the dictionary
  for i in dict:
      
    # If current element is even
    if dict[i] % 2 == 0:
        
      # Increase count of even
      even = even + 1
        
    # Otherwise
    else:
        
      # Increase count of odd
      odd = odd + 1
        
  print("Even count: ", even)
  print("Odd count: ", odd)
      
# Driver Code
  
# Given Dictionary
dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
  
countEvenOdd(dict)


输出:
Even Count:  2
Odd Count:  3

时间复杂度: O(N)
辅助空间: O(1)

替代方法:遍历字典中的每个项目,并针对每个元素检查它是偶数还是奇数。最后,打印相应的计数。

Python3

# Python3 Program to count even
# and odd elements in a dictionary
  
# Function to count even and
# odd elements in a dictionary
def countEvenOdd(dict):
  even = 0
  odd = 0
    
  # Iterate over the dictionary
  for i in dict:
      
    # If current element is even
    if dict[i] % 2 == 0:
        
      # Increase count of even
      even = even + 1
        
    # Otherwise
    else:
        
      # Increase count of odd
      odd = odd + 1
        
  print("Even count: ", even)
  print("Odd count: ", odd)
      
# Driver Code
  
# Given Dictionary
dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
  
countEvenOdd(dict)
输出:
Even count:  2
Odd count:  3

时间复杂度: O(N)
辅助空间: O(1)