Count Substring Occurrences
Python
Medium
4 views
Problem Description
Read two strings s and p. Write function count_occ(s,p) and output number of occurrences (overlap allowed).
Input Format
Two lines: s then p.
Output Format
One integer count.
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2: sys.exit(0)
s=lines[0].strip()
p=lines[1].strip()
def count_occ(a,b):
if b=='':
return 0
c=0
start=0
while True:
i=a.find(b,start)
if i==-1:
break
c+=1
start=i+1
return c
sys.stdout.write(str(count_occ(s,p)))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!