Exercise 78
Craft a Python algorithm that furnishes a list of indices where the specified occurrence, 'occ', is located within the provided string, 's.' Importantly!, refrain from utilizing any built-in methods such as find(), rfind(), or index(). In case 'occ' is absent in 's,' the function should yield an empty list, [].
For instance: if 's' = "Python is an interpreted language. Python is open source. Python is easy to learn" and 'occ' is "Python," the algorithm should yield the list: [0, 35, 58].
Solution
def find_occurrences(s, occ): occurrences = [] len_occ = len(occ) len_s = len(s) for i in range(len_s - len_occ + 1): if s[i:i+len_occ] == occ: occurrences.append(i) return occurrences # Example usage: s = "Python is an interpreted language. Python is open source. Python is easy to learn" occ = "Python" result = find_occurrences(s, occ) print(result) # output : [0, 35, 58]
Younes Derfoufi
CRMEF OUJDA
[…] Exercise 78** || Solution […]