Exercise 57
Write a python algorithm as a function which takes a tuple of string (s, s1) as input and which returns the number of the occurrences of s1 within the string s without using any predefined method. Example: if s = "Python is object oriented and dynamically typed " and s1 = "ed" , the function returns 2.
Solution
To solve this problem, we can use a loop to iterate through each character of the string s and check if the current character and the next len(s1) - 1 characters match with the string s1. If they match, we increment a counter variable:
def count_occurrences(s, s1): count = 0 for i in range(len(s) - len(s1) + 1): if s[i:i+len(s1)] == s1: count += 1 return count # Example: s = "Python is object oriented and dynamically typed" s1 = "ed" count = count_occurrences(s, s1) print(count) # Output: 2
Younes Derfoufi
CRMEF OUJDA
[…] Exercise 57 * || Solution […]