Python-courses-python-exercises-games-Python-courses-

Exercise 57

Write a python program as a function which takes as parameter a tuple of string (s, s1) and which returns the number of the occurrences of s1 within the string s. Example if s = "Python is object oriented and dynamically typed " and s1 = "ed" , the function returns 2

Solution

def numberOccurrences(s , s1):
n = len(s)
m = len(s1)

# initializing the number of occurrences of s1 wthin the string s.
occurrences = 0

for i in range(0 , n-m):
if s[i:i+m] == s1:
occurrences = occurrences + 1
return occurrences

s = "Python is object oriented and dynamically typed "
s1 = "ed"
print(numberOccurrences(s , s1)) # display 2

Younes Derfoufi
my-courses.net

Leave a Reply