Skip to content

Commit

Permalink
Add function for find_subseq.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Oct 13, 2022
1 parent 37799c1 commit 8d41c2d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
v6.3.0
======

Added ``find_subseq``.

v6.2.1
======

Expand Down
27 changes: 27 additions & 0 deletions jaraco/itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import heapq
import collections.abc
import queue
from typing import Iterable, Any

import inflect
import more_itertools
Expand Down Expand Up @@ -1213,3 +1214,29 @@ def accumulate(increments):
for item in items_:
value += item
yield value


def find_subseq(seq: Iterable[Any], cand: Iterable[Any]):
"""Find cand in seq.
Args:
seq: iterable of items to be searched
cand: iterable of items that must match
Returns:
The index where cand can be found in seq or None.
>>> find_subseq([-1, 0, 1, 2], [1, 2])
2
>>> find_subseq([-1, 0, 1, 2], [0, 2])
>>> find_subseq([-1, 0, 1, 2], [2, 1])
>>> find_subseq([-1, 0, 1, 2], [])
Traceback (most recent call last):
ValueError
"""
cand = tuple(cand)

def check(*window):
return window == cand
match_indexes = more_itertools.locate(seq, check, window_size=len(cand))
return next(match_indexes, None)

0 comments on commit 8d41c2d

Please sign in to comment.