Exercise 73
Write a function which takes as parameter a variable of type string s and another string T, and returns the list of positions of a pattern s in the string T. The function must return the empty list if the pattern s does not appear in the text T.
Solution
#function which determines the list of positions of s in the text T
def listPositions (T, s):
# initializing the list of s occurrences in T
lPosition = []
for i in range (0, len (T)):
# we test if the occurrence s is at position i
if T [i: len (s) + i] == s:
lPosition.append (i)
return lPosition
# Example
T = "Python is the most popular language and the most used language"
s = 'most'
print (listPositions (T, s)) # output: [14, 44]
Younes Derfoufi
my-courses.net
my-courses.net