Common characters between strings in an array

Viewed 103

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. After trying multiple times I am not able to get correct ans. What I am doing wrong here?

Expected Ans: {(c,1),(o,1)}

What I am getting: {('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)
3 Answers
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]: 

Try using functools.reduce and collections.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.

Related