There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in Language Help.
Agree with a comment or answer? Like () to up-vote the contribution!
Help!
I don’t understand why we add the index of the pattern to the index of the text for counting pattern matches. Can someone please walk me through the logic?
def pattern_search(text, pattern):
print("Input Text:", text, "Input Pattern:", pattern)
for index in range(len(text)):
print("Text Index:", index)
match_count = 0
for char in range(len(pattern)):
print("Pattern Index:", char)
if pattern[char] == text[index + char]:
print("Matching index found")
if pattern[char] == text[index + char]: <= this part
Super late, but basically you need it to make sure the correct index of the text is being checked. The char variables we get from range(len(pattern)) are indices of the pattern, not the text. If you just use the char to reference a text letter without adding index to it, you will only search the text using the pattern’s indices. The code will only keep checking the same indices at the beginning of the text.
For example, let’s say the first letter of the pattern, the letter at index 0, is at index 10 of the text. The if pattern[char] == text[index + char] will work out to if pattern[0] == text[10 + 0]. On the next iteration, it’ll check if the next letter of the pattern at index 1 matches the text at index 11: if pattern[1] == text[10 + 1].