user155876
user155876

Reputation: 361

Counting the number of times a character in string1 is found in string2?

I'm trying to create a function which takes two strings and then returns the sum total of how many times every character in the first string is found in the second string under the condition that duplicate characters in the first are ignored.

e.g. search_counter('aabbaa','a') would mean a count of 1 since the the second string only has one a and no bs and we only want to search for a once despite there being four as.

Here's my attempt so far:

def search_counter(search_string, searchme):
    count = 0
    for x in search_string:
        for y in searchme:
            if x == y:
                count = count + 1
    return count

The problem with my example is that there is no check to ignore duplicate characters in search_string. So instead of getting search_counter('aaa','a') = 1 I get 3.

Upvotes: 2

Views: 249

Answers (3)

muddyfish
muddyfish

Reputation: 3650

You can use iteration to do this

def search_counter(string, search):
    count = 0
    for i in range(len(string)):
        count += string[i:].startswith(search)
    return count

Or this one-liner

search_counter = lambda string, search: sum([string[i:].startswith(search) for i in range(len(string))])

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361585

for x in search_string:

You can get a list of characters without duplicates by converting the string to a set.

for x in set(search_string):

Upvotes: 3

salezica
salezica

Reputation: 76909

You can eliminate repetitions from a string by transforming it into a set:

>>> set("asdddd")
set(['a', 's', 'd'])

Preprocess your string this way, and the rest of the algorithm will remain the same (set objects are iterables, just like strings)

Upvotes: 1

Related Questions