I have a simple code for finding multiple pattern matching from a certain text (specifically for DNA sequence pattern matching)
text = "CTGATTCC"
pattern = "ATT", "CT", "TTT"
set = []
for x in pattern:
for i in range(0, len(text)-len(x)+1):
if text[i:(i+len(x))] == x:
set.append(i+1)
print("Positions:", set)
The code is already set, but I want to try if I can make the code print "Pattern is not found" for pattern that can’t be found in the text. I can’t figure out where to put it inside the loop. Any ideas would really help!
>Solution :
You can use a temporary list for each pattern, then verifying whether or not you found it
values = []
for x in pattern:
sub_values = []
for i in range(0, len(text) - len(x) + 1):
if text[i:i + len(x)] == x:
sub_values.append((x, i + 1))
if sub_values:
values.extend(sub_values)
else:
print("Pattern", x, "not found")
Pattern TTT not found
Positions: [('ATT', 4), ('CT', 1)]