Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Strings solution in Clear category for Count Substring Occurrences by Polundra
def count_occurrences(main_str: str, sub_str: str) -> int:
# your code here
if len(sub_str) > len(main_str):
return 0
s1 = main_str.lower()
s2 = sub_str.lower()
x = s1.count(s2)
if x == 0:
return 0
delta = len(s1) - len(s2)
res = 0
for i in range(delta+1):
if s1[i:i+len(s2)] == s2:
res +=1
return res
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!")
Nov. 21, 2023