猿问

在多个词典中查找常见字母 - python

我正在用给定的字符串制作代码返回字符。我知道使用计数器功能更容易使用,但我尽量不使用它。


这是我的代码


class Solution:

    def commonChars(self, A):

        dic = {}

        for i in range(len(A)):

            A[i] = list(A[i])

            dic[i] = self.checkLetter(A[i])

        print(dic)

        

    def checkLetter(self, Letter_list) : 

        letter_cnt = {}

        for l in Letter_list:

            if l in letter_cnt : letter_cnt[l] += 1

            else : letter_cnt[l] = 1

        return letter_cnt

我已经用字典制作了一个字母计数器,但我不知道下一步该做什么。你能给我一个提示吗?


# given input_1 : ["bella","label","roller"]

# expected output is e,l,l because it is common in every string in the given list

>>> ["e","l","l"]


# result of my code

>>> {0: {'a': 1, 'b': 1, 'e': 1, 'l': 2}, 1: {'a': 1, 'b': 1, 'e': 1, 'l': 2}, 2: {'r': 2, 'e': 1, 'l': 2, 'o': 1}}


# given input_2 : ["cool","lock","cook"]

# expected output

>>> ["c","o"]


至尊宝的传说
浏览 120回答 1
1回答

慕哥9229398

reduce.only 添加一行的可能解决方案:from functools import reduceclass Solution:    def commonChars(self, A):        dic = {}        for i in range(len(A)):            A[i] = list(A[i])            dic[i] = self.checkLetter(A[i])        print([char for char, count in reduce(lambda x, y:{k:min(x[k], y[k]) for k,v in x.items() if y.get(k)}, dic.values()).items() for _ in range(count)])    def checkLetter(self, Letter_list):        letter_cnt = {}        for l in Letter_list:            if l in letter_cnt:                letter_cnt[l] += 1            else:                letter_cnt[l] = 1        return letter_cnts = Solution()s.commonChars(["bella","label","roller"])# ['e', 'l', 'l']s.commonChars(["cool","lock","cook"])# ['c', 'o']拆分它:result_dict = reduce(lambda x, y:{k:min(x[k], y[k]) for k,v in x.items() if y.get(k)}, dic.values())print([char for char, count in result_dict.items() for _ in range(count)])
随时随地看视频慕课网APP

相关分类

Python
我要回答