使用計數器計算具有不同元素的子集的最小數量


為了表示這個問題中給定的專案集,必須存在最少數量的子組,並且每個子集包含唯一的成員。在這篇文章中,使用者將學習如何使用 Python 中的計數器獲得具有不同元素的子集的最小數量。本文描述了兩個例子。

示例一使用字典手動計算每個條目的例項,而示例二使用計數器類來計算具有唯一元素的子集的最小數量。為了計算列表中元素的例項,程式碼使用了 collections 模組中的 Counter 類。然後返回表示具有不同元件的元素集所需的子集的最小數量。該實現使得能夠快速準確地處理大型資料集。

讓我們從幾個例子開始:

使用字典計算元素的出現次數

程式碼解釋和設計步驟

  • 步驟 1 − 在 Anaconda 提示符中開啟 Jupyter Notebook 並開始在其單元格中編寫程式碼。

  • 步驟 2 − 首先必須定義函式‘count_distinct_subsets(elements)’,它接受一個元素列表作為輸入,並返回所需的子集的絕對最小數量。

  • 步驟 3 − 在函式內部初始化一個空字典‘counter’,該字典將用於儲存每個元素的計數。

  • 步驟 4 − 此字典將用於手動計算輸入列表中每個元素的出現次數。

  • 步驟 5 − 使用‘for’迴圈反覆迭代輸入列表中的每個條目。

  • 步驟 6 − 使用‘get()’方法,我們確定每個元素是否是計數器字典中的鍵。get() 方法返回與指定鍵關聯的值。

  • 步驟 7 − 如果元素不在字典中,‘get()’返回 0;否則,它返回該元素的當前計數。

  • 步驟 8 − 此過程使我們能夠更新字典並將計數增加 1。

  • 步驟 9 − 迭代完所有條目後,我們得到了一個包含輸入列表中每個元素計數的字典計數器。

  • 步驟 10 − 使用‘len(counter)’,我們透過獲取字典的長度來確定有多少個不同的元素。

  • 步驟 11 − 字典長度代表不同元素的數量,因為字典只能包含唯一的鍵。

  • 步驟 12 − 作為函式的最終輸出,它返回不同元素的總數。

示例 1

使用字典計算元素出現次數的程式碼:

def count_distinct_subsets(elements):
# Count the occurrences of each element in the input list
   counter = {}
   for element in elements:
      counter[element] = counter.get(element, 0) + 1
# Count the distinct elements
   distinct_elements = len(counter)

# Return the number of distinct elements
   return distinct_elements

elements = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
distinct_subsets = count_distinct_subsets(elements)
print(f"The minimum number of subsets required is: {distinct_subsets}")    

輸出

The minimum number of subsets required is: 4

檢視結果

程式碼中的函式‘count_distinct_subsets(elements)’計算表示給定元素集所需的不同子集的數量。該程式碼透過使用字典手動計算每個元素的例項來避免使用‘Counter’類。該函式在迴圈遍歷輸入列表時增加每個字典元素的計數。然後使用字典的長度確定不同元素的數量。該演算法為處理大型資料集提供了一種通用且有效的方法,並且可以應用於需要唯一子集的各種情況下。它使使用者能夠精確計算表示元素集所需的子集的絕對最小值,而無需任何重複元素。

在 Python 中使用 Counter 類

為了表示這個問題中給定的專案集,所需的子集的最小數量必須在每個子集中具有唯一的成員。我們將使用 Python 的‘Counter’類,這是一個有用的資料結構,用於跟蹤可迭代物件中每個元素出現的次數。

程式碼解釋和設計步驟:

  • 步驟 1 − 在 Anaconda 提示符中開啟 Jupyter Notebook 並開始在其單元格中編寫程式碼。

  • 步驟 2 − 首先從 collections 模組匯入 ‘Counter’ 類。

  • 步驟 3 − 函式 ‘count_distinct_subsets(elements)’ 接受一個元素列表作為輸入,並返回表示提供的元素集所需的子集的絕對最小數量,使得每個子集包含不同的元件。

  • 步驟 4 − 使用專案列表作為引數,我們在函式內部建立一個 Counter 物件 ‘counter’。這個 ‘counter’ 物件計算列表中每個元素的每個出現次數。

  • 步驟 5 − 使用 ‘len(counter)’,我們透過測量計數器物件的長度來確定有多少個不同的元素。

  • 步驟 6 − 最後,我們返回唯一元素的數量。

示例 2

使用計數器類的程式碼:

from collections import Counter

def count_distinct_subsets(elements):
   # Count the occurrences of each element in the input list
   counter = Counter(elements)

   # Count the distinct elements
   distinct_elements = len(counter)

   # Return the number of distinct elements
   return distinct_elements

elements = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
distinct_subsets = count_distinct_subsets(elements)
print(f"The minimum number of subsets required is: {distinct_subsets}")

輸出

The minimum number of subsets required is: 4

結論

在這篇文章中,使用兩個不同的例子,展示瞭如何使用計數器獲得具有不同元素的子集的最小數量的方法。這兩種演算法的實現使得它們能夠快速準確地處理大型資料集。

更新於:2023年10月18日

瀏覽量 123

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.