Подсчёт количества вхождений подстроки в строку
Пытаюсь реализовать программу подсчёта количества вхождений подстроки в строку на python. Не знаю почему в результате число вхождений равняется None.
s, t = input(), input()
count = 0
def define_number_of_includes(main, secondary):
global count
if main.find(secondary) != -1:
if main.startswith(secondary):
count = count + 1
main = main[1:]
print(count)
print(main)
define_number_of_includes(main, secondary)
if main.find(secondary) == -1:
return count
print(define_number_of_includes(s, t))
Ответы (1 шт):
Автор решения: E1mir
→ Ссылка
Алгоритм у вас не совсем верный, плюс не сильно оптимизированный. Даже если вы добавите return define_number_of_includes(main, secondary) то ничего не поменяется
main = 'hello world, this is subtext of my big text that contains several subtext words in this text which used for subtextsubtext subtext counter subtext'
sub = 'subtext'
count = 0
def define_number_of_includes(mainText, subtext):
global count
found_subtext_idx = mainText.find(subtext) # ищем, есть ли в строке данный подтекст
if found_subtext_idx != -1:
count += 1 # если есть, добавляем +1
# Берем и отрезаем уже найденный кусок текста
subtext_len = len(subtext)
next_start_idx = found_subtext_idx + subtext_len
next_part = mainText[next_start_idx:]
print(next_part)
return define_number_of_includes(next_part, subtext)
else:
return count
print(define_number_of_includes(main, sub))