Respuesta :

Answer:

I am writing a Python program:

import re

def NonOverlapping():

   string = input("Enter a string: ")

   substring = input("Enter a substring to find its non-overlapping occurances in " + string +": ")

   occurrences=len(re.findall(substring,string))

   return occurrences

print("The number of non-overlapping occurrences: " , NonOverlapping())

Explanation:

I will explain the program line by line.

import re  this is the module for performing regular expressions matching operations in Python.

def NonOverlapping(): this is the function definition. The function name is NonOverlapping and this function returns the number of non-overlapping occurrences of a substring in a string.

string = input("Enter a string: ")

substring = input("Enter a substring to find its non-overlapping occurances in " + string +": ")

The above two statement ares used to take input from the user. First the user is prompted to enter a string and the string is stored in string variable. Next user is asked to input the substring and its stored in susbtring variable.

occurrences=len(re.findall(substring,string)) This is the main line of the function. It has two methods i.e. len() and re.findall().

The re.findall() method returns all non-overlapping matches of substring in string. The string is checked for the given substring from left to right and all the non-overlapping occurrences of the substring are found and a list of matches is returned. len() method is used to return the length of the string but here it is used to count the number of non-overlapping occurrences substring in a string which are returned by re.findall() method. The whole result of these two methods is stored in occurrences.

return occurrences  This statement returns the number of non-overlapping occurrences of a substring in a string computed in the above statement.

print("The number of non-overlapping occurrences: " , NonOverlapping())

This statement displays the result by calling NonOveralling() method.

Ver imagen mahamnasir