asked 100.0k views
2 votes
write a python program to find out all index locations that has a certain pattern a string. (return a list, return [] if no such pattern in the string.)

asked
User NelDav
by
8.5k points

1 Answer

3 votes

Answer:

Sure, here's a Python program that finds all the index locations of a specified pattern in a given string and returns them as a list. If the pattern is not found in the string, an empty list is returned.

```python

def find_pattern_indexes(string, pattern):

indexes = []

n = len(string)

m = len(pattern)

for i in range(n-m+1):

if string[i:i+m] == pattern:

indexes.append(i)

return indexes

# example usage

string = "hello world, welcome to python programming"

pattern = "o"

indexes = find_pattern_indexes(string, pattern)

print(indexes) # output: [4, 7, 19, 27]

```

In this program, the `find_pattern_indexes` function takes two arguments: `string` and `pattern`. It uses a for loop to iterate over all possible substrings of length `m` (which is the length of the pattern) in the given string. If a substring matches the pattern, the index of the first character of the substring is added to the list of indexes. Finally, the function returns the list of indexes.

In the example usage, we use the function to find all the index locations of the letter "o" in the given string. The program outputs `[4, 7, 19, 27]`, which are the index locations of the letter "o" in the string.

Step-by-step explanation:

please follow me for more if you need any help

answered
User Royas
by
7.4k points

No related questions found