Advertisement
Guest User

Advancing an iterator until a subsequence is found

a guest
Dec 30th, 2015
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. from collections import deque
  4. from itertools import chain, islice
  5. from operator import ne
  6.  
  7. def dropuntil(iterable, needle):
  8.     """
  9.    Advance `iterable` until a sequence with all items of `needle` (with
  10.    respect to their order) is found. Then yield all remaining items
  11.    starting with the first item of `needle`. Yield nothing if `iterable`
  12.    does not contain the given needle.
  13.    """
  14.     iterator = iter(iterable)
  15.     window = deque(maxlen=len(needle))
  16.     window.extend(islice(iterator, len(needle)))
  17.     if len(window) == len(needle):
  18.         while any(map(ne, window, needle)):
  19.             try:
  20.                 window.append(next(iterator))
  21.             except StopIteration:
  22.                 return
  23.         yield from chain(window, iterator)
  24.  
  25. def main():
  26.     print(list(dropuntil([1,2,9,3,4,3,5,2,3,4,2,3], [2,3])))
  27.     print(list(dropuntil([1,2,9,3,4,3,5,2,3,4,2,3], [8,9])))
  28.     print(list(dropuntil([1,2,9,3,4,3,5,2,3,4,2,3], [])))
  29.     print(''.join(dropuntil('xxxhamyyyspamzzzeggs', 'spam')))
  30.  
  31. if __name__ == '__main__':
  32.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement