Question: Definition: A substring is a sequence of contiguous symbols within a string. For example: ana is a substring of banana , and umber is a

Definition: A substring is a sequence of contiguous symbols within a string. For example: ana is a substring of banana, and umber is a substring of cucumber. Every string is a substring of itself.
Python provides us a handy method for counting substrings within a string: .count(). For example, the word understandable contains two occurrences of the substring nd:
>>> "understandable".count("nd")
2
>>>
However, .count() doesnt handle overlapping substrings well. For example, the word banana contains two overlapping occurrences of the substring ana, but .count() only counts one:
>>> "banana".count("ana")
1
>>>
You are to write a function which counts occurrences of a substring within a string, including overlapping occurrences. So, for example, if the input to the function is banana, the function should return 2. We can look for other overlapping substrings in any arbitrary string. For example, in the string gactactaggacta has three occurrences of the substring acta(where two overlap). Notice also that a single letter is also a substring, so gactactaggacta contains 5 occurrences of the substring a.
The program
Write a program which prompts the user for a string and a substring and then reports the number of occurrences of the substring within the string, overlapping or otherwise. Examples of separate runs of such a program:
Enter a string: gactactaggacta
Enter a substring: acta
3
Enter a string: gactactaggacta
Enter a substring: a
5
Enter a string: gactactaggacta
Enter a substring: tag
1
Enter a string: gactactaggacta
Enter a substring: porcupine
0
For this you should write a function substring_count(). This function should take two arguments: the first argument should be the string to be searched, and the second argument should be the substring. This function should return an int, the number of occurrences found. This function should return 0 if the substring is not found or if the substring is the empty string.
You should implement this function without the use of any string methods, e.g.,.count(),.split(),.index(),.find(), etc. None of these is needed to solve the problem. The goal is to work with the elements of the string directly, using iteration and indexed reads.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!