1

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?

1
  • 3
    Simply iterate through it, you can it urself, I am sure. Commented Jul 22, 2018 at 11:15

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I can't upvote,because i haven't got enough reputation. And i accept this solution(click on the pipe),i hope it means accept,sorry if i did something badly,but i'm new here.
@JozefŠprlák You've done everything fine 😂😂 Thanks :)
3

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

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.