summaryrefslogtreecommitdiff
path: root/itertoolset.py
diff options
context:
space:
mode:
authorStan Seibert <stan@mtrr.org>2011-09-03 09:21:36 -0400
committerStan Seibert <stan@mtrr.org>2011-09-03 09:21:36 -0400
commit38f05bf761490def1886016524f328528b08f549 (patch)
treee0ee6555ee8bdf02a9e0b832a33707bcee06a3fa /itertoolset.py
parent48550062440c5b7f1479ecbe17fd4b024a90fca2 (diff)
parent707ca1b366f11032682cc864ca2848905e6b485c (diff)
downloadchroma-38f05bf761490def1886016524f328528b08f549.tar.gz
chroma-38f05bf761490def1886016524f328528b08f549.tar.bz2
chroma-38f05bf761490def1886016524f328528b08f549.zip
merge
Diffstat (limited to 'itertoolset.py')
-rw-r--r--itertoolset.py51
1 files changed, 42 insertions, 9 deletions
diff --git a/itertoolset.py b/itertoolset.py
index eb96e74..498b940 100644
--- a/itertoolset.py
+++ b/itertoolset.py
@@ -2,21 +2,54 @@ from itertools import *
import collections
from copy import deepcopy
+def peek(iterable):
+ """Peek at the first element of `iterable`.
+
+ Returns a tuple of the form (first_element, iterable).
+
+ Once peek() has been called, the original iterable will be modified if it
+ was an iterator (it will be advanced by 1); use the returned iterator for
+ an equivalent copy of the original iterable.
+ """
+ it = iter(iterable)
+ first_element = next(it)
+ return first_element, chain([first_element], it)
+
+def repeat_func(func, times=None, args=()):
+ "equivalent to (func(*args) for i in xrange(times))."
+ if times is None:
+ while True:
+ yield func(*args)
+ else:
+ for i in xrange(times):
+ yield func(*args)
+
+def repeat_copy(object, times=None):
+ """Returns deep copies of `object` over and over again. Runs indefinitely
+ unless the `times` argument is specified."""
+ if times is None:
+ while True:
+ yield deepcopy(object)
+ else:
+ for i in xrange(times):
+ yield object
+
def repeating_iterator(i, nreps):
- '''Returns an iterator that emits each element of `i` multiple times specified by `nreps`.
- The length of this iterator is the lenght of `i` times `nreps`. This iterator
- is safe even if the item consumer modifies the items.
+ """Returns an iterator that emits each element of `i` multiple times
+ specified by `nreps`. The length of this iterator is the lenght of `i`
+ times `nreps`. This iterator is safe even if the item consumer modifies
+ the items.
- >>> list(repeating_iterator('ABCD', 3)
- ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D']
- >>> list(repeating_iterator('ABCD', 1)
- ['A', 'B', 'C', 'D']
- '''
+ Examples:
+ >>> list(repeating_iterator('ABCD', 3)
+ ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D']
+ >>> list(repeating_iterator('ABCD', 1)
+ ['A', 'B', 'C', 'D']
+ """
for item in i:
for counter in xrange(nreps):
yield deepcopy(item)
-
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n