-3

Why is this giving output as 1 and not 2:

string = "ABCDCDC"
print(string.count("CDC"))

Also, since this is not working, how can I get 2 in this case?

Ank
  • 1,864
  • 4
  • 31
  • 51

4 Answers4

1

You could use a regular expression to count overlapping substrings:

import re
string = "ABCDCDC"
print(len(re.findall('(?=CDC)', string))) # 2
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
0

Here is an algorithmic solution

string = "ABCDCDC"
sub_string = "CDC"

count = 0
for i in range(len(string)):
    if string[i:len(sub_string)+i] == sub_string:
        count += 1 
print count
Kenan
  • 13,156
  • 8
  • 43
  • 50
0
import re
print([m.start() for m in re.finditer('(?=CDC)', 'ABCDCDC')])

This should find all potentially overlapping occurences

Rushabh Mehta
  • 1,529
  • 1
  • 13
  • 29
0

You can try this simple way:

def overlapping_count(string, seek):
    seek_len = len(seek)
    return sum(c == seek[0] and string[i:i + seek_len] == seek
                  for i, c in enumerate(string))
string = "ABCDCDC"
print(overlapping_count(string, "CDC"))
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45