Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON . Substring Count Write a pure function named subStringCount that accepts

ID: 3671845 • Letter: P

Question

PYTHON

. Substring Count Write a pure function named subStringCount that accepts two string arguments and counts the number of times a particular substring occurs within another string.

The first argument contains the substring and the second argument contains the full string. The function should count all occurrences of the substring including those that overlap:

def subStringCount(substr,fullstr):

Do not use the string method .count() and do not call input() or print() inside the subStringCount function.

Write a procedure named main that takes no arguments and does the following:

• Prompts the user and inputs a string from the console

• Prompts the user and inputs a substring from the console

• Calls subStringCount to determine the number of occurrences of substring in string

• Displays the result on the terminal display

Example:

enter a string: Mary had a little lamb, its fleece was white

enter a substring:

it it occurs 3 times

enter a string: 1212121

enter a substring: 121 121

occurs 3 times

Explanation / Answer

nStr = '000123000123'
pattern = '123'
count =0
flag=True
start=0
while flag:
a = nStr.find(pattern,start) # find() returns -1 if the word is not found,
#start i the starting index from the search starts(default value is 0)
if a==-1: #if pattern not found set flag to False
flag=False
else: # if word is found increase count and set starting index to a+1
count+=1
start=a+1
print(count)