📌  相关文章
📜  Python|通过字典交集查找三个排序数组中的公共元素

📅  最后修改于: 2022-05-13 01:54:48.072000             🧑  作者: Mango

Python|通过字典交集查找三个排序数组中的公共元素

给定三个按非降序排序的数组,打印这些数组中的所有公共元素。

例子:

Input:  ar1 = [1, 5, 10, 20, 40, 80]
        ar2 = [6, 7, 20, 80, 100]
        ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
Output: [80, 20]

Input:  ar1 = [1, 5, 5]
        ar2 = [3, 4, 5, 5, 10]
        ar3 = [5, 5, 10, 20]
Output: [5, 5]

我们有解决此问题的现有解决方案,请参阅 Find common elements in three sorted arrays 链接。我们可以使用字典的交集在Python中快速解决这个问题。做法很简单,

  1. 首先使用 Counter() 方法将所有三个列表转换为以元素为键、频率为值的字典。
  2. 现在对三个字典执行交集运算,这将导致我们的字典在三个数组列表中具有公共元素及其频率。
# Function to find common elements in three
# sorted arrays
from collections import Counter
  
def commonElement(ar1,ar2,ar3):
     # first convert lists into dictionary
     ar1 = Counter(ar1)
     ar2 = Counter(ar2)
     ar3 = Counter(ar3)
     
     # perform intersection operation
     resultDict = dict(ar1.items() & ar2.items() & ar3.items())
     common = []
      
     # iterate through resultant dictionary
     # and collect common elements
     for (key,val) in resultDict.items():
          for i in range(0,val):
               common.append(key)
  
     print(common)
  
# Driver program
if __name__ == "__main__":
    ar1 = [1, 5, 10, 20, 40, 80]
    ar2 = [6, 7, 20, 80, 100]
    ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
    commonElement(ar1,ar2,ar3)

输出:

[80, 20]