Find a string

Sort by

recency

|

3438 Discussions

|

  • + 0 comments

    It really tests your understanding of slicing and string traversal. If you're practicing for interviews or just want to strengthen your Python basics, Gurubhai247

  • + 1 comment

    string.count(sub_string) why this logic gives only 1

  • + 0 comments

    def count_substring(string, sub_string):

    count = 0
    index = 0       
    while index < len(string):
        found_at = string.find(sub_string, index)
        if found_at == -1:
            break
        count += 1
        index = found_at + 1
    return count
        if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)
    
  • + 0 comments
    def count_substring(string, sub_string):
        pointers = {}
        cnt = 0
        for i in range(len(string)):
            toPop = []
            # print(f"{pointers=}")
            for k in pointers:
                # print(f"{i=}, {k=}")
                if pointers[k] == len(sub_string): #matched
                    # print(f"{k=}")
                    cnt += 1
                    # print(f"Inc cnt for {k=}")
                    toPop.append(k)
                elif sub_string[pointers[k]] == string[i]: # in progress
                    pointers[k] += 1
                else: #not matched
                    toPop.append(k)
            for k in toPop: # get rid of the items already matched or not mached and keep the ones in progress
                # print(f"Popping {k=}")
                pointers.pop(k)
            if string[i] == sub_string[0] and (i <= len(string) - len(sub_string)):
                # start a new search
                pointers[str(i)] = 1
                # print("adding", i)
                
        for k in pointers:
            # print(f"final check: {i=}, {k=}")
            if pointers[k] == len(sub_string):
                # print(f"{k=}")
                cnt += 1
                # print(f"Inc cnt for {k=}")
        return cnt
            
    
    if __name__ == '__main__':
        string = input().strip()
        sub_string = input().strip()
        
        count = count_substring(string, sub_string)
        print(count)
    
  • + 0 comments
    def count_substring(string, sub_string):
        count = 0
        idx = -1
        while True:
            idx = string.find(sub_string, idx + 1)
            if idx != -1:
                count += 1
            else:
                break
        return count