Find a string in python - HackerRank solution
Solution for hackerRank problem Find a string in python
Problem :
In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.
NOTE: String letters are case-sensitive.
Input Format
The first line of input contains the original string. The next line contains the substring.
Constraints
1 <= len(string) <= 200
Each character in the string is an ascii character.
Output Format
Output the integer number indicating the total number of occurrences of the substring in the original string.
Sample Input
ABCDCDC
CDC
Sample Output
2
Concept
len(s)
, where is the string.for i in range(0, len(s)):
print (s[i])
A range function is used to loop over some length:
range (0, 5)
Here, the range loops over to . is excluded.
Procedure
1. Start.
2. Store the first letter of the sub string in a variable.
3. Initialize count as 0.
4. Loop from 0 to len(string)
=> if s[i] = first letter of sub string
=> loop from 0 to length of the sub string
=> check if each character of the string is equal to the corresponding character in the sub string
=> if all characters are equal then increment the count variable.
5. Print the count.
6. End.
Code :
def count_substring(string, sub_string):
first = sub_string[0]
count=0
for i in range(len(string)):
if(string[i]==first):
flag=0
for x in range(len(sub_string)):
if((i+x)<len(string)):
if(string[i+x]==sub_string[x]):
continue
else :
flag = 1
break
else :
flag=1
if(flag==0):
count+=1
return count
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
Comments
Post a Comment