1

For a hackerrank challenge to print the number of times that the substring occurs in the given string, I wrote attached logic. But I keep receiving 0 has output. Please share comments on the logic where missing.

To print the number of times that the substring occurs in the given string

def count_substring(string, sub_string):
    count = 0
    for i in range(0,len(string)):
        if(sub_string== string[i:i+len(sub_string)]):
            count= ++count 
    return count
if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(count)

Input for string and sub_string is ABCDCDC,CDC

Expected output is 2, but the actual Result 0

Shanmukha Reddy
  • 81
  • 1
  • 10
  • Also note that you dont have to go all the way to `len(string)` lets say the length of the string is 10 and the length of the substring is 4, you would be checking `sub_string== string[9:13]` which never going to be true. You can save some iterations by doing `for i in range(0,len(string)-len(substring)+1)` – Davo Dec 22 '18 at 22:10

2 Answers2

0

count=++count does not work in Python (see e.g. Behaviour of increment and decrement operators in Python), it should be count+=1, then your code works as expected.

Bart
  • 9,825
  • 5
  • 47
  • 73
-1

Bug is in your count = ++count line Change this to count += 1

AnkurJat
  • 404
  • 3
  • 9