Replace the window() example with pairwise() which demonstrates tee().

This commit is contained in:
Raymond Hettinger 2003-10-26 15:34:50 +00:00
parent f0c5aec85f
commit d591f666de
2 changed files with 14 additions and 23 deletions

View file

@ -405,15 +405,9 @@ def repeatfunc(func, times=None, *args):
else: else:
return starmap(func, repeat(args, times)) return starmap(func, repeat(args, times))
def window(seq, n=2): def pairwise(iterable):
"Returns a sliding window (of width n) over data from the iterable" "s -> (s0,s1), (s1,s2), (s2, s3), ..."
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " a, b = tee(iterable)
it = iter(seq) return izip(a, islice(b, 1, None))
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
\end{verbatim} \end{verbatim}

View file

@ -623,16 +623,10 @@ Samuele
... else: ... else:
... return starmap(func, repeat(args, times)) ... return starmap(func, repeat(args, times))
>>> def window(seq, n=2): >>> def pairwise(iterable):
... "Returns a sliding window (of width n) over data from the iterable" ... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
... " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " ... a, b = tee(iterable)
... it = iter(seq) ... return izip(a, islice(b, 1, None))
... result = tuple(islice(it, n))
... if len(result) == n:
... yield result
... for elem in it:
... result = result[1:] + (elem,)
... yield result
This is not part of the examples but it tests to make sure the definitions This is not part of the examples but it tests to make sure the definitions
perform as purported. perform as purported.
@ -681,10 +675,13 @@ False
>>> take(5, imap(int, repeatfunc(random.random))) >>> take(5, imap(int, repeatfunc(random.random)))
[0, 0, 0, 0, 0] [0, 0, 0, 0, 0]
>>> list(window('abc')) >>> list(pairwise('abcd'))
[('a', 'b'), ('b', 'c')] [('a', 'b'), ('b', 'c'), ('c', 'd')]
>>> list(window('abc',5)) >>> list(pairwise([]))
[]
>>> list(pairwise('a'))
[] []
>>> list(islice(padnone('abc'), 0, 6)) >>> list(islice(padnone('abc'), 0, 6))