Find a String Hackerrank

Question:

Input:ABCDCDC
CDC
Output:2

def count_substring(string, sub_string):
        for i in range(0,len(string)):
            ans=string.count(sub_string)
            return ans

I am getting 1 as output how can I get 2 as output and read the full string

Asked By: Shaik Basha

||

Answers:

def count_substring(string, sub_string):
  return {s: string.count(s) for s in set(string)}

OUTPUT:

{' ': 1, 'B': 1, 'A': 1, 'D': 3, 'C': 5}
Answered By: s0mbre

From every index look forward for next n characters if they match, n being the size of substring

def count_substring(string, sub_string):
    n = len(sub_string)
    ans = 0
    for i in range(0,len(string)):
        if(i+n > len(string)):#out of range problem
            break
        ans+=string.count(sub_string,i,i+n)
    return ans
Answered By: Mareek Roy

My solution was: for each character, check if the string from that specific character begins with the sub string required, so that overlapping ones are accounted for too

def count_substring(string, sub_string):
  total = 0
  for i in range(len(string)):
      if string[i:].startswith(sub_string):
          total += 1
  return total
Answered By: Ammar

In my solution, I have made a list and added all the n numbered words from the string so that I can count from the list the number of words= sub_string.

def count_substring(string, sub_string):
a=len(sub_string) # for finding the length of substring
b=[] # initializing a list
c=0 # initializing a counter variable
for i in range(len(string)):
    if a+i<=len(string):
        b.append(string[i:a+i])
for i in b:
    if i==sub_string:
        c=c+1
return c

if __name__ == '__main__':
   string = input().strip()
   sub_string = input().strip()
   count = count_substring(string, sub_string)
   print(count)
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.