简体   繁体   English

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

[英]Common characters between strings in an array

I am trying to find the common char between the strings in the array.我试图在数组中的字符串之间找到公共字符。 I am using a hashmap for this purpose which is defined as Counter.为此,我使用 hashmap 定义为计数器。 After trying multiple times I am not able to get correct ans.多次尝试后,我无法获得正确的答案。 What I am doing wrong here?我在这里做错了什么?

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

What I am getting: {('c', 1)}我得到的是:{('c', 1)}

My code:我的代码:

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)

Try using functools.reduce and collections.Counter :尝试使用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})

An approach without any other library could be like this:没有任何其他库的方法可能是这样的:

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

This should give you the result formated as you want it.这应该为您提供所需格式的结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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