使用 Python 查找数组中出现频率最低的元素


在这篇文章中,我们将学习获取数组中出现频率最低的元素的 Python 程序。

使用的方法

以下是完成此任务的各种方法:

  • 使用 sort() 函数(朴素方法)

  • 使用哈希

  • 使用 Counter() 函数

方法 1:使用 sort() 函数(朴素方法)

运行两个循环是一个简单的解决方法。外循环逐个选择每个元素。内循环计算所选元素的频率,并将其与迄今为止达到的最小值进行比较。此解决方案的时间复杂度为 O(n^2)

排序是一个更好的解决方案。首先对数组进行排序,然后线性遍历它,我们就可以找到出现频率最低的元素,如下面的代码所示。

示例

以下程序使用 sort() 函数返回输入数组/列表中出现频率最低的元素:

# creating a function for returning the least frequent element
def leastFrequencyElement(inputList, listLength):
   # sorting the given input list
   inputList.sort()
   # Setting the minimum frequency(minimum count) as length of list + 1
   minimumCount = listLength + 1
   resultElement = -1
   # Variable to count the frequency
   currentCount = 1
   # Looping from 1st index to the length of the list
   for k in range(1, listLength):
      # Check if the previous element is equal to the current element
      if (inputList[k] == inputList[k - 1]):
         #Increase the frequency of the current element by 1
            currentCount = currentCount + 1
      else:
         # Check if the current Count is less than the minimum Count
            if (currentCount < minimumCount):
               #If it is true then set the minimum count as current Count value
                  minimumCount = currentCount
                  # Store this previous element as the least frequent element
                  resultElement = inputList[k - 1]
            # Resetting the current Count as 1
            currentCount = 1
   # checking whether the last element is less frequent
      if (currentCount < minimumCount):
         minimumCount = currentCount
         resultElement = inputList[listLength - 1]
   # returning the least frequent element
      return resultElement
# input list
inputList = [6, 5, 5, 4, 4, 2, 2, 2, 1, 1]
print("Given List is:", inputList)
# getting list length
listLength = len(inputList)
# calling the leastFrequencyElement function by passing
# input list and list length as arguments
print("Least frequent element in the input list is:")
print(leastFrequencyElement(inputList, listLength))

输出

执行上述程序将生成以下输出:

Given List is: [6, 5, 5, 4, 4, 2, 2, 2, 1, 1]
Least frequent element in the input list is:
6

方法 2:使用哈希

应用哈希是一个有效的解决方案。在此方法中,我们创建一个哈希表并存储元素及其频率计数作为键值对。然后,我们遍历哈希表并打印具有最小值的键。

示例

以下程序使用哈希返回输入数组/列表中出现频率最低的元素:

# creating a function for returning the least frequent element
# by accepting the input list and input list length as arguments
def leastFrequencyElement(inputList, listLength):
   # Take a dictionary as a hash table
   HashTable = dict()
   # Loop in the given list
   for k in range(listLength):
      # Check if the list element in the hashtable
         if inputList[k] in HashTable.keys():
            # If it is present then increase the frequency by 1
               HashTable[inputList[k]] += 1
         else:
            # Else create a new key with the frequency as 1
               HashTable[inputList[k]] = 1
   #  Setting the minimum frequency(minimumCount) as length of list + 1
   minimumCount = listLength + 1
   resultElement = -1
   # Iterating the hashtable(dictionary)
   for k in HashTable:
      # Check if the minimum count is greater or equal to the frequency of the key
         if (minimumCount >= HashTable[k]):
            #If it is true then this key will be the current least frequent element
               resultElement = k
            # Set the minimum count as the current key frequency value
               minimumCount = HashTable[k]

   # returning the least frequent element
   return resultElement
# input list
inputList = [3, 10, 3, 1, 5, 5, 4, 4, 2, 2, 2, 1, 1]
# getting list length
listLength = len(inputList)
print("Given List is:", inputList)
print("Least frequent element in the input list is:")
# calling the leastFrequencyElement function by passing
# input list and list length as arguments
print(leastFrequencyElement(inputList, listLength))

输出

执行上述程序将生成以下输出:

Given List is: [3, 10, 3, 1, 5, 5, 4, 4, 2, 2, 2, 1, 1]
Least frequent element in the input list is:
10

方法 3:使用 Counter() 函数

Counter() 函数(将单词的频率作为键值对返回)

示例

以下程序使用 Counter() 函数返回输入数组/列表中出现频率最低的元素:

# importing Counter from the collections module
from collections import Counter
# creating a function for returning the least frequent element
# by accepting the input list and input list length as arguments
def leastFrequencyElement(inputList, listLength):
   # getting the frequency of all elements of a list
   hashTable = Counter(inputList)
   # Setting the minimum frequency(minimumCount) as length of list + 1
   minimumCount = listLength + 1
   # Variable to store the resultant least frequent element
   resultElement = -1
   # iterating the hash table
   for k in hashTable:
         # Check if the minimum count is greater or equal to the frequency of the key
            if (minimumCount >= hashTable[k]):
               # If it is true then this key will be the current least frequent element
                  resultElement = k
            # Set the minimum count as the current key frequency value
            minimumCount = hashTable[k]
# returning the least frequent element
   return resultElement
# input list
inputList = [3, 10, 3, 1, 5, 5, 4, 4, 2, 2, 2, 1, 1]
# getting list length
listLength = len(inputList)
print("The Given List is:", inputList)
print("Least frequent element in the input list is:")
# calling the leastFrequencyElement function by passing
# input list and list length as arguments
print(leastFrequencyElement(inputList, listLength))

输出

执行上述程序将生成以下输出:

The Given List is: [3, 10, 3, 1, 5, 5, 4, 4, 2, 2, 2, 1, 1]
Least frequent element in the input list is:
10

结论

在本文中,我们学习了如何使用三种不同的方法在给定列表中查找出现频率最低的元素。我们还学习了如何在 Python 中执行哈希,我们可以使用它来获取所有唯一元素,在 O(1) 时间内搜索等等。我们学习了如何使用 Counter() 函数执行哈希。

更新于:2023年1月23日

824 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.