Counter教程

Python 函数Counter的学习

Leetcode intersection of two arrays II

Problem:Given two arrays, write a function to compute their intersection.
Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Notes:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:

What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

1. 看到问题,最简单的想法就是利用两循环来进行相同值的比对寻找,这是最简单当然也是最复杂的解法

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        intersectionNums=[]
        for i in range(len(nums1)):
            for j in range (len(nums2)):
                if nums1[i]==nums[j]:
                    intersectionNums.extend[nums1[i]]
                    intersectionNums.extend[nums2[j]]
        return intersectionNums

现在再看一遍这个代码,都觉得自己 too young too naive 根本没有理解题目的意思
假设 nums1=[1,2,2,1],nums2=[2] 最后会返回一个[2,2]

2.寻找其他解法,可以将list转换成set来进行求交集

# intersection=[i for i in nums1 if i in nums2]
# intersection=list(set(nums1).intersection(set(nums2)))
# 这都是将转化成set来进行求交集
class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        if len(nums1)<=len(nums2):
            return [i for i in nums1 if i in nums2]
        else:
            return [i for i in nums2 if i in nums1]

为什么要添加判断两个数组的长度?
Submission Result: Wrong Answer
Input: [3,1,2]
[1,1]
Output: [1,1]
Expected: [1]

虽然可以控制循环不会溢出的问题
但是会导致输出重复的问题

3.寻找大神的解法,看了一下讨论区,可以利用Counter module 来进行求交集

先info(man) 或者 help(Counter)

from collections import Counter

help(Counter)

Help on class Counter in module collections:
class Counter(builtins.dict)
| Dict subclass for counting hashable items. Sometimes called a bag
| or multiset. Elements are stored as dictionary keys and their counts
| are stored as dictionary values.
|
| >>> c = Counter(‘abcdeabcdabcaba’) # count elements from a string
|
| >>> c.most_common(3) # three most common elements
| [(‘a’, 5), (‘b’, 4), (‘c’, 3)]
| >>> sorted(c) # list all unique elements
| [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
| >>> ”.join(sorted(c.elements())) # list elements with repetitions
| ‘aaaaabbbbcccdde’
| >>> sum(c.values()) # total of all counts
| 15
|
| >>> c[‘a’] # count of letter ‘a’
| 5
| >>> for elem in ‘shazam’: # update counts from an iterable
| … c[elem] += 1 # by adding 1 to each element’s count
| >>> c[‘a’] # now there are seven ‘a’
| 7
| >>> del c[‘b’] # remove all ‘b’
| >>> c[‘b’] # now there are zero ‘b’
| 0

利用 Counter 建立一个列表中元素,以及元素个数一一对应的字典 
>>> from collections import Counter
>>> help(Counter)

>>> a=[1,2,2,3,3,4,4,4]
>>> Counter(a)
Counter({4: 3, 2: 2, 3: 2, 1: 1})
>>> 
# 思路就是先建立两个字典,将nums1,nums2的元素及个数一一对应后放入到字典中存储
# 在两个字典中寻找即是相同的元素,也有相同的个数进行求解
# 返回需求的元素.也就是字典对应的value
class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        from collections import Counter
        c1 = Counter(nums1)
        c2 = Counter(nums2)
        return list((c1&c2).elements()) # 返回一个list 
    # Elements are stored as dictionary keys and their counts
 |  # are stored as dictionary values.

人生苦短,我选Python!

猜你喜欢

转载自blog.csdn.net/qq_37904945/article/details/79899791