A sequence of overlapping subsequences >>> list(sliding_window(2, [1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4)] This function creates a sliding window suitable for transformations like sliding means / smoothing >>> mean = lambda seq: float(sum(seq)) / len(seq) >>> list(map(mean,
(n, seq)
| 32 | |
| 33 | |
| 34 | def sliding_window(n, seq): |
| 35 | """A sequence of overlapping subsequences |
| 36 | |
| 37 | >>> list(sliding_window(2, [1, 2, 3, 4])) |
| 38 | [(1, 2), (2, 3), (3, 4)] |
| 39 | |
| 40 | This function creates a sliding window suitable for transformations like |
| 41 | sliding means / smoothing |
| 42 | |
| 43 | >>> mean = lambda seq: float(sum(seq)) / len(seq) |
| 44 | >>> list(map(mean, sliding_window(2, [1, 2, 3, 4]))) |
| 45 | [1.5, 2.5, 3.5] |
| 46 | """ |
| 47 | import collections |
| 48 | import itertools |
| 49 | |
| 50 | return zip( |
| 51 | *( |
| 52 | collections.deque(itertools.islice(it, i), 0) or it |
| 53 | for i, it in enumerate(itertools.tee(seq, n)) |
| 54 | ), |
| 55 | strict=False, |
| 56 | ) |
no outgoing calls
no test coverage detected
searching dependent graphs…