Existing?
As part of a larger project, I thought I might need to search for a sub-list within a given list, and because I am lazy i did a quick google and did not like the answers I found.I started with the thought that the best algorithm for me would be to start searching from the index of the first item in the sublist and so on, but none of the googled answers used list.index.
I decided then to create my own
My version
Well I want to use list.index. If the item is not in the list then it raises an error, so I'll need a try-except block too.
I look for successive first item from the sub-list in the list and if found, accumulate the index in the answer and move on to search for the next match.
It seemed easy to add flags to:
- Stop after finding a first index of the sub-list in the list.
- Allow overlapping matches or not. [1,0,1] is found twice in [1,0,1,0,1] at indices 0 and 2, but only once if overlapping is not allowed
STOP PRESS!
A Reddit commenter spotted a bug that I fixed and added a couple of extra tests for.
End.