简体   繁体   中英

Find common alphabets in multiple dictionaries - python

I'm making the code returning character with given strings. I know it is easier to use when using the counter function but I'm trying not to use it.

here is my code

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

I've done making a letter counter with a dictionary but I have no clue what to do next. could you give me a hint?

# 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"]

Possible solution with reduce .only add one line:

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']

Split it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM