Python 数组中字符串之间的公共字符
我试图在数组中的字符串之间找到公共字符。为此,我使用了一个hashmap,它被定义为Counter。在多次尝试后,我无法获得正确的答案。我在这里做错了什么 预期Ans:{(c,1),(o,1)} 我得到的:{('c',1)} 我的代码:Python 数组中字符串之间的公共字符,python,string,algorithm,dictionary,hashmap,Python,String,Algorithm,Dictionary,Hashmap,我试图在数组中的字符串之间找到公共字符。为此,我使用了一个hashmap,它被定义为Counter。在多次尝试后,我无法获得正确的答案。我在这里做错了什么 预期Ans:{(c,1),(o,1)} 我得到的:{('c',1)} 我的代码: arr = ["cool","lock","cook"] def Counter(arr): d ={} for items in arr: if items no
arr = ["cool","lock","cook"]
def Counter(arr):
d ={}
for items in arr:
if items not in d:
d[items] = 0
d[items] += 1
return d
res = Counter(arr[0]).items()
for items in arr:
res &= Counter(items).items()
print(res)
尝试使用和:
尝试使用和:
没有任何其他库的方法可能是这样的:
arr = ["cool","lock","cook"]
def Counter(obj_str):
countdict = {x: 0 for x in set(obj_str)}
for char in obj_str:
countdict[char] += 1
return {(k, v) for k,v in countdict.items()}
print(Counter(arr[0]))
这将为您提供所需格式的结果。没有任何其他库的方法可能是这样的:
arr = ["cool","lock","cook"]
def Counter(obj_str):
countdict = {x: 0 for x in set(obj_str)}
for char in obj_str:
countdict[char] += 1
return {(k, v) for k,v in countdict.items()}
print(Counter(arr[0]))
In [29]: from collections import Counter
In [30]: words = ["cool","coccoon","cook"]
In [31]: chars = ''.join(set(''.join(words)))
In [32]: counts = [Counter(w) for w in words]
In [33]: common = {ch: min(wcount[ch] for wcount in counts) for ch in chars}
In [34]: answer = {ch: count for ch, count in common.items() if count}
In [35]: answer
Out[35]: {'c': 1, 'o': 2}
In [36]:
这将为您提供所需格式的结果。记住向已回答的人反馈。记住向已回答的人反馈。
In [29]: from collections import Counter
In [30]: words = ["cool","coccoon","cook"]
In [31]: chars = ''.join(set(''.join(words)))
In [32]: counts = [Counter(w) for w in words]
In [33]: common = {ch: min(wcount[ch] for wcount in counts) for ch in chars}
In [34]: answer = {ch: count for ch, count in common.items() if count}
In [35]: answer
Out[35]: {'c': 1, 'o': 2}
In [36]: