Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Count Substring Occurrences by mennadiego
def count_occurrences(main_str: str, sub_str: str) -> int:
counter = 0
i = 0
indice_vecchio = -1
main_str = main_str.lower()
sub_str = sub_str.lower()
while i < len(main_str):
if main_str.find(sub_str, i) != -1:
indice_trovato = main_str.find(sub_str, i)
if indice_trovato != indice_vecchio:
counter += 1
indice_vecchio = indice_trovato
i += 1
return counter
print("Example:")
print(count_occurrences("hello world hello", "hello"))
# These "asserts" are used for self-checking
assert count_occurrences("hello world hello", "hello") == 2
assert count_occurrences("Hello World hello", "hello") == 2
assert count_occurrences("hello", "world") == 0
assert count_occurrences("hello world hello world hello", "world") == 2
assert count_occurrences("HELLO", "hello") == 1
assert count_occurrences("appleappleapple", "appleapple") == 2
assert count_occurrences("HELLO WORLD", "WORLD") == 1
assert count_occurrences("hello world hello", "o w") == 1
assert count_occurrences("apple apple apple", "apple") == 3
assert count_occurrences("apple Apple apple", "apple") == 3
assert count_occurrences("apple", "APPLE") == 1
print("The mission is done! Click 'Check Solution' to earn rewards!")
April 6, 2024