Find a string | HackerRank
Find the number of occurrences of a substring in a string.
www.hackerrank.com
Goal
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.
Solution
The function starts by initializing the number variable to zero, which will be used to keep track of the count of the number of times sub_string occurs in string.
Then, it calculates the length of string and stores it in the n variable.
The function then enters a loop that will iterate n times.
In each iteration, the function uses the find method to search for the first occurrence of sub_string in the new_string variable.
If the find method returns -1, it means that sub_string is not found in new_string and the loop increments the index i by 1.
If find returns a value other than -1, it means that sub_string has been found, and the function increments the number count by 1.
The new_string is then updated to start from the position just after the found sub_string.
Finally, the function returns the number count, which is the number of times sub_string occurs in string.
# Find a string
def count_substring(string, sub_string):
number = 0
n = len(string)
new_string = string
for i in range(0, n):
result = new_string.find(sub_string)
if(result == -1):
new_string = new_string[i:]
i += 1
else:
new_string = new_string[result + 1:]
i = result + 1
number += 1
return number
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
'software Engineering > (Python)HackerRank' 카테고리의 다른 글
[Python] HackerRank - Text Wrap (0) | 2023.02.17 |
---|---|
[Python] HackerRank - String Validators (0) | 2023.02.16 |
[Python] HackerRank - Mutations (0) | 2023.02.14 |
[Python] HackerRank - What's Your Name? (0) | 2023.02.11 |
[Python] HackerRank - String Split and Join (0) | 2023.02.07 |