0

How I could solve this error:

if pattern[i] == txt[i]: IndexError: string index out of range

txt = "ABCDCDC"
pattern = "CDC"

count = 0
i = 0

for index in range(0, len(txt) + 1):
    if pattern[i] == txt[i]:
        if txt[i:i + len(pattern)] == pattern:
            count = count + 1
            print(count)
    i = i + 1

print(count)

1 Answer 1

0

Assuming you are trying to find the number of times that the pattern occurs in the txt (with overlapping allowed), the following should work! It was erroring because you were using the indices for txt which wouldn't work for all indices of the pattern (i.e. pattern[3] doesn't exist).

txt = "ABCDCDC"
pattern = "CDC"

count = 0

for i in range(len(txt) - len(pattern) + 1):
    if txt[i: i + len(pattern)] == pattern:
        count += 1
print(count)
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.