-1

I am trying to solve for the below function. I am getting my expected empty tuple when the sub is not found in the given string 'text'. However, I am having a problem incrementing during the for-loop to find the subsequent positions of the same sub in the remainder of the string 'text'.

def findall(text,sub):
    """
    Returns the tuple of all positions of substring sub in text.
    
    If sub does not appears anywhere in text, this function returns the 
    empty tuple ().
    
    Examples:
        findall('how now brown cow','ow') returns (1, 5, 10, 15)
        findall('how now brown cow','cat') returns ()
        findall('jeeepeeer','ee') returns (1,2,5,6)
    
    Parameter text: The text to search
    Precondition: text is a string
    
    Parameter sub: The substring to search for
    Precondition: sub is a nonempty string
    """
    tup = ()
    
    for pos in range(len(text)):
        if sub not in text:
            tup = ()
        else:
            pos1 = introcs.find_str(text,sub)
            tup = tup + (pos1,)
            # increment to the next pos and look for the sub again, not sure how to
            # move beyond the first instance of the substring in the text ???
            pos1 = pos1 + 1
            
    return tup
KV1
  • 65
  • 7
  • You can use slicing to refer to part of a string. For instance, if mystr = "hello world", then mystr[2:] would just be "llo world". – Malkoun Apr 23 '21 at 04:06
  • hmm, not sure how to cycle through the full unknown string to search for the given subtext. I get slicing, just not sure how to slice on an unknown string in this particular example. – KV1 Apr 23 '21 at 04:12
  • @KV1 You can slice with variables, not just integer literals. `string[index:]` would give you everything from `index` to the end, for instance. – CrazyChucky Apr 23 '21 at 04:31

1 Answers1

0

I think your problem will be solved easily with regular expressions best refer to this answer but if you insist on making it your way what about you delete the substring once you find it and then the position of the next substring will be the previous one + the length of the substring something like that. For example for findall('how now brown cow','ow') first the position is 1 we delete the susbtring we are left with 'h now brown cow','ow' then the position returned by find will be 3 + substring.length = 5 which is the actual position of the susbstring ... Try it out hope it helps

Souha Gaaloul
  • 328
  • 4
  • 9