Finding the number of times characters from text1 occur in text2

def occurrences(text1, text2):
"""Return the number of times characters from text1 occur in text2

occurrences(string, string) -> int
"""
text1_dict = {char:0 for char in text1}

for char in text2:
    if char in text1_dict:
        text1_dict[char] += 1

return sum(list(text1_dict.values()))

I wrote a code that solves this in O(n) instead of O(n^3)
it makes a dict ouf of text1’s chars, that counts occurance of each char in text 2
then it counts text2’s chars and update the dict.
finally it returns the sum of the values (unfortunatly you cant do sum on the dict values so i used list before).

Leave a Comment