Find a substring count in an string

Posted on

Problem

This code is written to find substring count in a string in Python 3. The original problem description is here. Please suggest better ways of solving this.

string =input()
substring = input()
count = 0
i=0
while(i<(len(string)-len(substring))):
    if(string.find(substring,i,len(string))>=0):
        count+=1
        i=string.find(substring,i,len(string))+1
    else:
        break;
print(count)

Solution

KISS (Keep it simple, stupid)

You could’ve done this way simpler than that by just writing:

string.count(substring)

Wrapping this into a function for later use would look like:

def count_substrings(my_string, my_substring):
    return my_string.count(my_substring)

if __name__ == '__main__':
    print(count_substrings('dexter is dexter lala dext dexter', 'dexter'))

Which will print the desired result:

3

About your code:

  1. You should always have a space around operators (i=0 should be i = 0).
  2. Python is not C. You have way too many parentheses and you shouldn’t use ;.

There’s something called PEP8 which is the recommended style-guide for Python. I’d strongly recommend you read it.

Your code would look like this if we’d respect the above:

string = input()
substring = input()

count, i = 0, 0
while i < len(string) - len(substring):
    if string.find(substring, i, len(string)) >= 0:
        count += 1
        i = string.find(substring, i, len(string)) + 1
    else:
        break
print(count)

More, I’d let the user know what’s about to be entered so I’d write:

my_string = input('Please enter the string: ')
my_substring = input('What substring are you looking for? ')

You should also wrap your code within a function for later use, and add the if __name__ == '__main__' construction, which will allow you you to have that code execute only when you want to run the module as a program, and not have it execute when someone just wants to import your module and call your functions themselves


Anyway, the first solution does not work for overlapping matches (which I saw it was a requirement after reading the challenge), so you might consider doing it like you did, but a bit different / simpler:

def count_substrings(my_string, my_substring):
    count = start = 0
    while True:
        start = my_string.find(my_substring, start) + 1
        if start > 0:
            count += 1
        else:
            return count

The above might be even faster since it does the comparing in C.


Bear with the fact that I’ve only commented on your actual code, and not the entire challenge. You might wanna add some constraints which are clearly specified there (e.g: 1 <= len(my_string) <= 200)

Leave a Reply

Your email address will not be published.