2

In my code I try to found index of the pattern, count every comparison and I also want to stop this algorithm then my pattern is too long for comparison to rest of the text. Something is wrong with counter and I couldn't stop algorithm. I am beginner and I don't have idea what to do.

def search(W, T):
    count = 0
    for i in range(len(T) - len(W) + 1):
        if i > len(T)-len(W):
            break
        j = 0
        while(j < len(W)):
            if (T[i  + j] != W[j]):
                count += 1
                break
            j += 1
            
        if (j == len(W)):
            count += len(W)
            print("Pattern found at index ", i, count)
 
if __name__ == '__main__':
    T = "AABAACAADAABAAABAA"
    W = "AABA"

    search(W, T)

Thanks for helping.

I expect that someone will change my code or tell me what to do.

1 Answer 1

2

First of all, as you are a beginner in Python here's some tips:

  1. You do not need brackets in if: if j == len(W): is ok, moreover these brackets are against PEP8 codestyle.
  2. You don't need this condition:
    if i > len(T)-len(W):
        break

range() is smart guy. He won't let i be more then len(T)-len(W)

Now to your question, here's the solution (I hope, that I understand what do you want)

def search(W, T):
    count = 0
    for i in range(len(T) - len(W) + 1):
        j = 0
        while j < len(W):
            if T[i + j] != W[j]:
                count += 1
                break
            j += 1
            count += 1

        if j == len(W):
            print("Pattern found at index ", i, count)


if __name__ == '__main__':
    T = "AABAACAADAABAAABAA"
    W = "AABA"

    search(W, T)

The problem was that you increment your counter only when you founded the pattern or when you failed to find it. Here's example:

T = AAABAAA

W = AABA

In your solution counter would be incremented only on the 3d letter "A" while it should be incremented after each comparison.

I hope everything is clear. Good luck in studying!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.