Skip to content

Commit 6fe0a6b

Browse files
[3.12] sliding_window() recipe: Raise ValueError for non-positive window sizes. Add more tests. (GH-105403) (GH-105405)
1 parent bf62e06 commit 6fe0a6b

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

Doc/library/itertools.rst

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -929,9 +929,7 @@ which incur interpreter overhead.
929929
def sliding_window(iterable, n):
930930
# sliding_window('ABCDEFG', 4) --> ABCD BCDE CDEF DEFG
931931
it = iter(iterable)
932-
window = collections.deque(islice(it, n), maxlen=n)
933-
if len(window) == n:
934-
yield tuple(window)
932+
window = collections.deque(islice(it, n-1), maxlen=n)
935933
for x in it:
936934
window.append(x)
937935
yield tuple(window)
@@ -1420,8 +1418,34 @@ The following recipes have a more mathematical flavor:
14201418
>>> list(grouper('abcdefg', n=3, incomplete='ignore'))
14211419
[('a', 'b', 'c'), ('d', 'e', 'f')]
14221420

1421+
>>> list(sliding_window('ABCDEFG', 1))
1422+
[('A',), ('B',), ('C',), ('D',), ('E',), ('F',), ('G',)]
1423+
>>> list(sliding_window('ABCDEFG', 2))
1424+
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]
1425+
>>> list(sliding_window('ABCDEFG', 3))
1426+
[('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
14231427
>>> list(sliding_window('ABCDEFG', 4))
14241428
[('A', 'B', 'C', 'D'), ('B', 'C', 'D', 'E'), ('C', 'D', 'E', 'F'), ('D', 'E', 'F', 'G')]
1429+
>>> list(sliding_window('ABCDEFG', 5))
1430+
[('A', 'B', 'C', 'D', 'E'), ('B', 'C', 'D', 'E', 'F'), ('C', 'D', 'E', 'F', 'G')]
1431+
>>> list(sliding_window('ABCDEFG', 6))
1432+
[('A', 'B', 'C', 'D', 'E', 'F'), ('B', 'C', 'D', 'E', 'F', 'G')]
1433+
>>> list(sliding_window('ABCDEFG', 7))
1434+
[('A', 'B', 'C', 'D', 'E', 'F', 'G')]
1435+
>>> list(sliding_window('ABCDEFG', 8))
1436+
[]
1437+
>>> try:
1438+
... list(sliding_window('ABCDEFG', -1))
1439+
... except ValueError:
1440+
... 'zero or negative n not supported'
1441+
...
1442+
'zero or negative n not supported'
1443+
>>> try:
1444+
... list(sliding_window('ABCDEFG', 0))
1445+
... except ValueError:
1446+
... 'zero or negative n not supported'
1447+
...
1448+
'zero or negative n not supported'
14251449

14261450
>>> list(roundrobin('abc', 'd', 'ef'))
14271451
['a', 'd', 'e', 'b', 'f', 'c']

0 commit comments

Comments
 (0)