Stack Overflow Asked by Ns68 on January 3, 2021
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)])
Correct answer by jizhihaoSAMA on January 3, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP