为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

至尊宝的传说 2023-05-09 14:49:31
我正在用给定的字符串制作代码返回字符。我知道使用计数器功能更容易使用,但我尽量不使用它。这是我的代码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"]
查看完整描述

1 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

reduce.only 添加一行的可能解决方案:


from functools import reduce



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([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_cnt



s = 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)])


查看完整回答
反对 回复 2023-05-09
  • 1 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信