Finding a string multiple times in another String - Python

后端 未结 7 1381
死守一世寂寞
死守一世寂寞 2021-01-22 12:00

I\'m trying to see if a string exists in another string with out using Python\'s predefined functions such as find and index..

Right now what my function takes 2 strings

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-22 12:36

    Note: I think this answer here is still a good "teaching answer", I have submitted a better solution elsewhere in this thread, without recursion.

    def multi_find(s, r, start=0):
        if start >= len(s): 
            return []
        if s.startswith(r, start):
            return [start] + multi_find(s, r, start+1)
        else:
            return multi_find(s, r, start+1)
    

    This allows you to pass an optional start position to begin the search in s.

    This solution is recursive, which may or may not be the fastest implementation, but it is correct and I believe it makes the code easy to identify each of the three possibilities at each position of s:

    1. end of s
    2. found another r
    3. didn't find another r

提交回复
热议问题