Now that we are looping through both the
text and the
pattern, we can begin to compare the two to check for matches. For each character of the
text, we want to check if the subsequent characters match the
pattern. These matches will then be counted to later determine if the
pattern exists in the
While iterating over the
pattern indices, the first character of the
pattern can be compared to the currently iterated character of the
text with the following comparison:
if pattern == text[index]: # Do something
To make the above comparison more dynamic, and compare the entirety of the
pattern, the current
char index can be added to both of the above indices.
Inside the for loop iterating the
pattern indices, create a conditional statement to check if the current character in the
pattern at the
char index is equal to the current character in the
char plus the
If this conditional is true, print
"Matching index found".
for loop, moving on to the next index in the text, as it doesn’t make sense to continue counting if a match doesn’t exist.
Since we are now checking for matches, let’s start counting them as well. Between printing the
"Text Index:" and iterating through the
pattern indices, set a new variable
match_count equal to
0. Then, every time the conditional comparing the
text indices evaluates to
True, print the current value of
match_count with the label
"Match Count:" before incrementing it by
Our code is nearing completion, and it has all of the information in place to check if a pattern exists in the text.
After we have iterated through all of the indices in the pattern, check if
match_count equals the length of the
match_count equals the length of
pattern then print a helpful message mentioning that the contents of the
pattern variable were found inside of the input text.
The message should read as follows:
<pattern value> found at index <index value>