aoc2021/libs/sliding.py

27 lines
719 B
Python
Raw Normal View History

2021-12-02 00:23:47 +00:00
def sliding(iterable,window=1):
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
from itertools import tee
a, b = tee(iterable)
IT = [ ]
for _ in range(window):
next(b, None)
return zip(a, b)
def sliding_window(iterable, n):
from collections import deque
from itertools import islice
# sliding_window('ABCDEFG', 4) -> ABCD BCDE CDEF DEFG
it = iter(iterable)
window = deque(islice(it, n), maxlen=n)
#window = deque(it, maxlen=n)
if len(window) == n:
yield tuple(window)
for x in it:
window.append(x)
yield tuple(window)
import sys
print([t for t in sliding_window(map(lambda x: int(x[:-1]), sys.stdin.readlines()),4)])
#print(a for a in sliding(map(lambda x: int(x[:-1]), sys.stdin.readlines()),3))