Shaik Basha
Shaik Basha

Reputation: 5

Find a String Hackerrank

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

Upvotes: 0

Views: 3921

Answers (5)

Hajiagapyth
Hajiagapyth

Reputation: 1

def count_substring(string, sub_string):
lis = list(string)
M = list(sub_string)
d = 0
w = 0
for i in range(len(lis)-(len(M)-1)):
    if lis[i] == M[0]:
        d = 0
        for k in range(len(M)):
            if M[k] == lis[k+i]:
                d+=1
            else:
                break
        if d == len(M):
            w+=1
                
return w

I used more complex method because I didn't want to use any built-in function.

Upvotes: 0

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)

Upvotes: 0

Ammar
Ammar

Reputation: 138

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

Upvotes: 3

Mareek Roy
Mareek Roy

Reputation: 45

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

Upvotes: 0

s0mbre
s0mbre

Reputation: 574

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}

Upvotes: 0

Related Questions