数组中字符串之间的常见字符



我正在尝试查找数组中字符串之间的公共字符。为此,我使用了一个hashmap,它被定义为Counter。经过多次尝试,我都没有得到正确的答案。我做错了什么?

预期答案:{(c,1(,(o,1(}

我得到的是:{('c',1(}

我的代码:

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

尝试使用functools.reducecollections.Counter:

>>> from functools import reduce
>>> from collections import Counter
>>> reduce(lambda x,y: x&y, (Counter(elem) for elem in arr[1:]), Counter(arr[0]))
Counter({'c': 1, 'o': 1})

没有任何其他库的方法可能是这样的:

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

这应该会给你想要的格式化结果

最新更新