I am using a search pattern algorithm to find a pat(list) items in a txt(list). This function is supposed to return the index value of the list txt.
def search(pat, txt):
M = len(pat)
N = len(txt)
# A loop to slide pat[] one by one */
for i in range(N - M 1):
j = 0
# For current index i, check
# for pattern match */
while(j < M):
if (txt[i j] != pat[j]):
break
j = 1
if (j == M):
print("Pattern found at index ", i)
# Driver's Code
txt = ["GA","07","09","07","0H"]
pat = ["GA","09","0H"]
for i in pat:
for y in txt:
if i == y:
if __name__ == '__main__':
# Function call
search(pat, txt)
I have modified the above code. But this does not work. However, in the original code, if one item is provided to pat it works, and if more than one item is provided to pat, it collapses and does not show anython. Here is original code.
# Python3 program for Naive Pattern
# Searching algorithm
def search(pat, txt):
M = len(pat)
N = len(txt)
# A loop to slide pat[] one by one */
for i in range(N - M 1):
j = 0
# For current index i, check
# for pattern match */
while(j < M):
if (txt[i j] != pat[j]):
break
j = 1
if (j == M):
print("Pattern found at index ", i)
# Driver's Code
if __name__ == '__main__':
txt = ["GA","07","09","07","0H"]
pat = ["07"]
# Function call
search(pat, txt)
Please provide more than one item to pat(list) and execute. I need this Naive search pattern algorithm to find all items of pat(list) in txt(list) and return index. For example
pat = ["GA","09","0H"]
CodePudding user response:
Try this:
indices = []
for x in pat:
try:
indices.append(txt.index(x))
except ValueError:
pass
Example with txt = ['GA', '07', '09', '07', '0H']
and pat = ['GA', '09', '0H']
:
>>> indices
[0, 2, 4]
CodePudding user response:
If you want to get index and item:
[list(filter(lambda item: item[1] == pat_item, enumerate(txt)))[0] for pat_item in pat]
output:
[(0, 'GA'), (2, '09'), (4, '0H')]
If you want to get just index:
[list(filter(lambda item: item[1] == pat_item, enumerate(txt)))[0][0] for pat_item in pat]
output:
[0, 2, 4]