]> granicus.if.org Git - python/commitdiff
Replace the window() example with pairwise() which demonstrates tee().
authorRaymond Hettinger <python@rcn.com>
Sun, 26 Oct 2003 15:34:50 +0000 (15:34 +0000)
committerRaymond Hettinger <python@rcn.com>
Sun, 26 Oct 2003 15:34:50 +0000 (15:34 +0000)
Doc/lib/libitertools.tex
Lib/test/test_itertools.py

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