leetcode daily question: 1002. Find common characters

Keywords: Python Algorithm leetcode

leetcode daily question: 1002. Find common characters

Title Description: given A string array A composed of only lowercase letters, return A list composed of all characters (including repeated characters) displayed in each string in the list. For example, if A character appears 3 times in each string, but not 4 times, you need to include the character 3 times in the final answer.

You can return answers in any order.

Example 1:

Input: ["bella", "label", "roller"]
Output: ["e", "l", "l"]
Example 2:

Input: ["cool", "lock", "cook"]
Output: ["c", "o"]

Tips:

1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter
Number of passes 38527 number of submissions 52200

Source: LeetCode
Link: https://leetcode-cn.com/problems/find-common-characters
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Today's problem is easy, but it's not easy at all. It involves a series of knowledge

The idea is simple and the code is simpler:

class Solution:
    def commonChars(self, A: List[str]) -> List[str]:
        return reduce(lambda x,y:x&y, map(Counter,A)).elements()

feel surprised? feel off-guard? Just one line

The idea is nothing more than counting the number of each letter in each word, building a hashtable, and then taking the intersection of multiple hashtables to get the final desired result

How many knowledge points are contained in this line of code? Let's say it slowly:

reduce()

This function comes from the functools library. We need to execute it first

from functools import reduce

describe

The reduce() function accumulates the elements in the parameter sequence.

The function performs the following operations on all data in a data set (linked list, tuple, etc.): first operate the first and second elements in the set with the function (with two parameters) passed to reduce, then operate with the third data with the function function, and finally get a result.

grammar

reduce() function syntax:

reduce(function, iterable[, initializer])

parameter

  • Function – function with two parameters
  • Iteratable – iteratable object
  • initializer – optional, initial parameter

Return value

Returns the result of the function calculation.

example

The following example shows how to use reduce():

>>>def add(x, y) :            # Add two numbers 
...     return x + y
...  
>>> reduce(add, [1,2,3,4,5])   # Calculation list and: 1 + 2 + 3 + 4 + 5 
15 
>>> reduce(lambda x, y: x+y, [1,2,3,4,5])  # Using lambda anonymous functions 
15

map()

describe

map() maps the specified sequence according to the provided function.

The first parameter function calls the function function with each element in the parameter sequence and returns a new list containing the return value of each function function.

grammar

map() function syntax:

map(function, iterable, ...)

parameter

  • Function – function
  • iterable – one or more sequences

Return value

Python 2.x returns a list.

Python 3.x returns an iterator.

example

The following example shows how to use map():

>>>def square(x) :            # Calculate square 
...     return x ** 2 
...  
>>> map(square, [1,2,3,4,5])   # Calculate the square of each element of the list [1, 4, 9, 16, 25] 
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # Using lambda anonymous functions 
[1, 4, 9, 16, 25]  
# Two lists are provided to add the list data at the same location 
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) 
[3, 7, 11, 15, 19]

There is also one of the most important:

collections.Counter class

Counter: used to track the number of occurrences of a value

The Counter class inherits the dict class, so it can use the methods in the dict class

Create a Counter class

import collections
obj = collections.Counter('aabbccc')
print(obj)

#Output: Counter({'c': 3, 'a': 2, 'b': 2})

elements()

import collections
obj = collections.Counter('aabbccc')
print(sorted(obj.elements()))

#Output: ['a ',' a ',' B ',' B ',' C ',' C ',' C ']

for k in obj.elements():   #Traverse and print obj all elements
    print(k)

most_ Common (specify a parameter n and list the first n elements; if no parameter is specified, list all elements)

import collectionsobj = collections.Counter('aabbbcccc')print(obj.most_common(2))#Output: [('c ', 4), (B', 3)]

Items (Methods inherited from dict class)

import collectionsobj = collections.Counter('aabbbcccc')print(obj.items())for k,v in obj.items():    print(k,v)#Output: dict_items([('b', 3), ('c', 4), ('a', 2)])#     b 3#     c 4#     a 2

Update (add element)

import collectionsobj = collections.Counter(['11','22'])obj.update(['22','55'])print(obj)#Output: Counter({'22': 2, '11': 1, '55': 1})

Subtract (the original element minus the newly passed in element)

import collectionsobj = collections.Counter(['11','22','33'])obj.subtract(['22','55'])print(obj)#Output: Counter({'11': 1, '33': 1, '22': 0, '55': -1})

Thanks for watching. Any questions are welcome!

Posted by cwiddowson on Sun, 19 Sep 2021 21:26:59 -0700