Jozef Šprlák
Jozef Šprlák

Reputation: 39

Count function Python

I want to make a function that does the same thing as count, without using count. Something like this:

>>> count('mama ma emu a ema ma mamu', 'ma ')
4
>>> count('mama ma emu a ema ma mamu', 'am')
2

How could I acheive this?

Upvotes: 1

Views: 5449

Answers (3)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

You can try this list comprehension:

def count(s,ss):
    return sum(1 for e in range(len(s)-len(ss)+1) if s[e:e+len(ss)]==ss)

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195593

Is using re allowed?

import re

def count(text, s):
    return len(re.findall(s, text))

print(count('mama ma emu a ema ma mamu', 'ma '))
print(count('mama ma emu a ema ma mamu', 'am'))

Prints:

4
2

Upvotes: 3

Adi219
Adi219

Reputation: 4814

I thought I'd add an iterative approach where you loop through the string as it would be easier to understand.

Try this:

def count(string, substring):

    count = 0

    for i in range(len(string) - len(substring) + 1):
        if string[i: i + len(substring)] == substring:
            count += 1

    return count

Essentially, I'm iterating through the possible values of i, where i is the starting index of each substring which is of the same length as the substring entered. Then, I'm simply checking if each possible substring of the correct length is equivalent to the substring entered. If so, I increment my count by 1.

Upvotes: 3

Related Questions