#πŸ”’ sliding window help

18 messages Β· Page 1 of 1 (latest)

loud horizon
#

given two strings s1 and pattern
find how many substrings in s that is equal to string pattern

i knew the algo for this is sliding window, but im havin a difficult time coding it up, any help is appriciated.

def sliding(s1):
            # sliding window
            l, r = 0, 0
            i = 0
            count = 0
        
            print(s1)
            while r < len(s1):
                if i + 1 == len(pattern):
                    count += 1
                    i = 0
                    
                char = s1[r]
                # if valid char
                if i + 1 < len(pattern) and char == pattern[i]:
                    # proceed with this, it is good
                    i += 1

                # not valid char
                else:
                    # check if i + 1 == len(pattern) cuz if so it is 1 cell found
                    i = 0
                    l += 1
                    while l < r and s1[l] != pattern[i]:
                        l += 1

                print(s1[r],r, l)
                r += 1
                        
            return count
solid flowerBOT
#

@loud horizon

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

loud horizon
patent garden
#

it looks like you never define pattern is there any more code you have?

loud horizon
#

ah yes its input fields

patent garden
#

also, do you get any errors? or does the program just not work?

loud horizon
#

in this case

#

s1 = "aaccbbbcaabacaacaacc"
pattern = "abaca"

it should return 1 but 0 is returned

patent garden
#

there's probably some small detail in your algorithm that's going wrong. I'd try to look at it step by step and identify exactly where it's different from expected

loud horizon
loud horizon
#

ahhhhhh i see

#

i shouldn't move the r pointer there

#

wait whats the point of 2 pointers here

solid flowerBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.