我正在使用给定的字符串使代码返回字符。我知道使用计数器功能时更容易使用,但我尽量不使用它。
这是我的代码
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
Run Code Online (Sandbox Code Playgroud)
我已经用字典制作了一个字母计数器,但我不知道下一步该做什么。你能给我一个提示吗?
# 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"]
Run Code Online (Sandbox Code Playgroud)
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']
Run Code Online (Sandbox Code Playgroud)
拆分它:
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)])
Run Code Online (Sandbox Code Playgroud)