blob: 9da51aa5378fab6431668943cc2dd858d6752b82 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`itertools` --- Functions creating iterators for efficient looping
3=======================================================================
4
5.. module:: itertools
6 :synopsis: Functions creating iterators for efficient looping.
7.. moduleauthor:: Raymond Hettinger <python@rcn.com>
8.. sectionauthor:: Raymond Hettinger <python@rcn.com>
9
10
Georg Brandl9afde1c2007-11-01 20:32:30 +000011This module implements a number of :term:`iterator` building blocks inspired by
Georg Brandl116aa622007-08-15 14:28:22 +000012constructs from the Haskell and SML programming languages. Each has been recast
13in a form suitable for Python.
14
15The module standardizes a core set of fast, memory efficient tools that are
16useful by themselves or in combination. Standardization helps avoid the
17readability and reliability problems which arise when many different individuals
18create their own slightly varying implementations, each with their own quirks
19and naming conventions.
20
21The tools are designed to combine readily with one another. This makes it easy
22to construct more specialized tools succinctly and efficiently in pure Python.
23
24For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a
25sequence ``f(0), f(1), ...``. This toolbox provides :func:`imap` and
26:func:`count` which can be combined to form ``imap(f, count())`` and produce an
27equivalent result.
28
29Likewise, the functional tools are designed to work well with the high-speed
30functions provided by the :mod:`operator` module.
31
32The module author welcomes suggestions for other basic building blocks to be
33added to future versions of the module.
34
35Whether cast in pure python form or compiled code, tools that use iterators are
36more memory efficient (and faster) than their list based counterparts. Adopting
37the principles of just-in-time manufacturing, they create data when and where
38needed instead of consuming memory with the computer equivalent of "inventory".
39
40The performance advantage of iterators becomes more acute as the number of
41elements increases -- at some point, lists grow large enough to severely impact
42memory cache performance and start running slowly.
43
44
45.. seealso::
46
47 The Standard ML Basis Library, `The Standard ML Basis Library
48 <http://www.standardml.org/Basis/>`_.
49
50 Haskell, A Purely Functional Language, `Definition of Haskell and the Standard
51 Libraries <http://www.haskell.org/definition/>`_.
52
53
54.. _itertools-functions:
55
56Itertool functions
57------------------
58
59The following module functions all construct and return iterators. Some provide
60streams of infinite length, so they should only be accessed by functions or
61loops that truncate the stream.
62
63
64.. function:: chain(*iterables)
65
66 Make an iterator that returns elements from the first iterable until it is
67 exhausted, then proceeds to the next iterable, until all of the iterables are
68 exhausted. Used for treating consecutive sequences as a single sequence.
69 Equivalent to::
70
71 def chain(*iterables):
72 for it in iterables:
73 for element in it:
74 yield element
75
76
Christian Heimes70e7ea22008-02-28 20:02:27 +000077.. function:: itertools.chain.from_iterable(iterable)
78
79 Alternate constructor for :func:`chain`. Gets chained inputs from a
80 single iterable argument that is evaluated lazily. Equivalent to::
81
82 @classmethod
83 def from_iterable(iterables):
84 for it in iterables:
85 for element in it:
86 yield element
87
88 .. versionadded:: 2.6
89
Christian Heimes836baa52008-02-26 08:18:30 +000090.. function:: combinations(iterable, r)
91
92 Return successive *r* length combinations of elements in the *iterable*.
93
Christian Heimes70e7ea22008-02-28 20:02:27 +000094 Combinations are emitted in lexicographic sort order. So, if the
Christian Heimes836baa52008-02-26 08:18:30 +000095 input *iterable* is sorted, the combination tuples will be produced
96 in sorted order.
97
98 Elements are treated as unique based on their position, not on their
99 value. So if the input elements are unique, there will be no repeat
Christian Heimes70e7ea22008-02-28 20:02:27 +0000100 values in each combination.
Christian Heimes836baa52008-02-26 08:18:30 +0000101
102 Each result tuple is ordered to match the input order. So, every
103 combination is a subsequence of the input *iterable*.
104
Christian Heimes836baa52008-02-26 08:18:30 +0000105 Equivalent to::
106
107 def combinations(iterable, r):
Christian Heimesb558a2e2008-03-02 22:46:37 +0000108 'combinations(range(4), 3) --> (0,1,2) (0,1,3) (0,2,3) (1,2,3)'
Christian Heimes836baa52008-02-26 08:18:30 +0000109 pool = tuple(iterable)
Christian Heimes380f7f22008-02-28 11:19:05 +0000110 n = len(pool)
Christian Heimesb558a2e2008-03-02 22:46:37 +0000111 indices = range(r)
112 yield tuple(pool[i] for i in indices)
Christian Heimes380f7f22008-02-28 11:19:05 +0000113 while 1:
114 for i in reversed(range(r)):
Christian Heimesb558a2e2008-03-02 22:46:37 +0000115 if indices[i] != i + n - r:
Christian Heimes836baa52008-02-26 08:18:30 +0000116 break
Christian Heimes380f7f22008-02-28 11:19:05 +0000117 else:
118 return
Christian Heimesb558a2e2008-03-02 22:46:37 +0000119 indices[i] += 1
Christian Heimes380f7f22008-02-28 11:19:05 +0000120 for j in range(i+1, r):
Christian Heimesb558a2e2008-03-02 22:46:37 +0000121 indices[j] = indices[j-1] + 1
122 yield tuple(pool[i] for i in indices)
Christian Heimes836baa52008-02-26 08:18:30 +0000123
124 .. versionadded:: 2.6
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126.. function:: count([n])
127
128 Make an iterator that returns consecutive integers starting with *n*. If not
Georg Brandl9afde1c2007-11-01 20:32:30 +0000129 specified *n* defaults to zero. Often used as an argument to :func:`imap` to
130 generate consecutive data points. Also, used with :func:`izip` to add sequence
131 numbers. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133 def count(n=0):
134 while True:
135 yield n
136 n += 1
137
Georg Brandl116aa622007-08-15 14:28:22 +0000138
139.. function:: cycle(iterable)
140
141 Make an iterator returning elements from the iterable and saving a copy of each.
142 When the iterable is exhausted, return elements from the saved copy. Repeats
143 indefinitely. Equivalent to::
144
145 def cycle(iterable):
146 saved = []
147 for element in iterable:
148 yield element
149 saved.append(element)
150 while saved:
151 for element in saved:
152 yield element
153
154 Note, this member of the toolkit may require significant auxiliary storage
155 (depending on the length of the iterable).
156
157
158.. function:: dropwhile(predicate, iterable)
159
160 Make an iterator that drops elements from the iterable as long as the predicate
161 is true; afterwards, returns every element. Note, the iterator does not produce
162 *any* output until the predicate first becomes false, so it may have a lengthy
163 start-up time. Equivalent to::
164
165 def dropwhile(predicate, iterable):
166 iterable = iter(iterable)
167 for x in iterable:
168 if not predicate(x):
169 yield x
170 break
171 for x in iterable:
172 yield x
173
174
175.. function:: groupby(iterable[, key])
176
177 Make an iterator that returns consecutive keys and groups from the *iterable*.
178 The *key* is a function computing a key value for each element. If not
179 specified or is ``None``, *key* defaults to an identity function and returns
180 the element unchanged. Generally, the iterable needs to already be sorted on
181 the same key function.
182
183 The operation of :func:`groupby` is similar to the ``uniq`` filter in Unix. It
184 generates a break or new group every time the value of the key function changes
185 (which is why it is usually necessary to have sorted the data using the same key
186 function). That behavior differs from SQL's GROUP BY which aggregates common
187 elements regardless of their input order.
188
189 The returned group is itself an iterator that shares the underlying iterable
190 with :func:`groupby`. Because the source is shared, when the :func:`groupby`
191 object is advanced, the previous group is no longer visible. So, if that data
192 is needed later, it should be stored as a list::
193
194 groups = []
195 uniquekeys = []
196 data = sorted(data, key=keyfunc)
197 for k, g in groupby(data, keyfunc):
198 groups.append(list(g)) # Store group iterator as a list
199 uniquekeys.append(k)
200
201 :func:`groupby` is equivalent to::
202
203 class groupby(object):
204 def __init__(self, iterable, key=None):
205 if key is None:
206 key = lambda x: x
207 self.keyfunc = key
208 self.it = iter(iterable)
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000209 self.tgtkey = self.currkey = self.currvalue = object()
Georg Brandl116aa622007-08-15 14:28:22 +0000210 def __iter__(self):
211 return self
212 def __next__(self):
213 while self.currkey == self.tgtkey:
214 self.currvalue = next(self.it) # Exit on StopIteration
215 self.currkey = self.keyfunc(self.currvalue)
216 self.tgtkey = self.currkey
217 return (self.currkey, self._grouper(self.tgtkey))
218 def _grouper(self, tgtkey):
219 while self.currkey == tgtkey:
220 yield self.currvalue
221 self.currvalue = next(self.it) # Exit on StopIteration
222 self.currkey = self.keyfunc(self.currvalue)
223
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. function:: ifilter(predicate, iterable)
226
227 Make an iterator that filters elements from iterable returning only those for
228 which the predicate is ``True``. If *predicate* is ``None``, return the items
Georg Brandlf6945182008-02-01 11:56:49 +0000229 that are true. This function is the same as the built-in :func:`filter`
230 function. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000231
232 def ifilter(predicate, iterable):
233 if predicate is None:
234 predicate = bool
235 for x in iterable:
236 if predicate(x):
237 yield x
238
239
240.. function:: ifilterfalse(predicate, iterable)
241
242 Make an iterator that filters elements from iterable returning only those for
243 which the predicate is ``False``. If *predicate* is ``None``, return the items
244 that are false. Equivalent to::
245
246 def ifilterfalse(predicate, iterable):
247 if predicate is None:
248 predicate = bool
249 for x in iterable:
250 if not predicate(x):
251 yield x
252
253
254.. function:: imap(function, *iterables)
255
256 Make an iterator that computes the function using arguments from each of the
Georg Brandlf6945182008-02-01 11:56:49 +0000257 iterables. This function is the same as the built-in :func:`map` function.
258 Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260 def imap(function, *iterables):
Raymond Hettinger1dfde1d2008-01-22 23:25:35 +0000261 iterables = [iter(it) for it in iterables)
Georg Brandl116aa622007-08-15 14:28:22 +0000262 while True:
Raymond Hettinger1dfde1d2008-01-22 23:25:35 +0000263 args = [next(it) for it in iterables]
Christian Heimes1af737c2008-01-23 08:24:23 +0000264 if function is None:
265 yield tuple(args)
266 else:
267 yield function(*args)
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269
270.. function:: islice(iterable, [start,] stop [, step])
271
272 Make an iterator that returns selected elements from the iterable. If *start* is
273 non-zero, then elements from the iterable are skipped until start is reached.
274 Afterward, elements are returned consecutively unless *step* is set higher than
275 one which results in items being skipped. If *stop* is ``None``, then iteration
276 continues until the iterator is exhausted, if at all; otherwise, it stops at the
277 specified position. Unlike regular slicing, :func:`islice` does not support
278 negative values for *start*, *stop*, or *step*. Can be used to extract related
279 fields from data where the internal structure has been flattened (for example, a
280 multi-line report may list a name field on every third line). Equivalent to::
281
282 def islice(iterable, *args):
283 s = slice(*args)
Georg Brandlf6945182008-02-01 11:56:49 +0000284 it = range(s.start or 0, s.stop or sys.maxsize, s.step or 1)
Georg Brandl116aa622007-08-15 14:28:22 +0000285 nexti = next(it)
286 for i, element in enumerate(iterable):
287 if i == nexti:
288 yield element
289 nexti = next(it)
290
291 If *start* is ``None``, then iteration starts at zero. If *step* is ``None``,
292 then the step defaults to one.
293
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295.. function:: izip(*iterables)
296
297 Make an iterator that aggregates elements from each of the iterables. Like
298 :func:`zip` except that it returns an iterator instead of a list. Used for
299 lock-step iteration over several iterables at a time. Equivalent to::
300
301 def izip(*iterables):
302 iterables = map(iter, iterables)
303 while iterables:
304 result = [next(it) for it in iterables]
305 yield tuple(result)
306
Georg Brandl55ac8f02007-09-01 13:51:09 +0000307 When no iterables are specified, return a zero length iterator.
Georg Brandl116aa622007-08-15 14:28:22 +0000308
Christian Heimes1af737c2008-01-23 08:24:23 +0000309 The left-to-right evaluation order of the iterables is guaranteed. This
310 makes possible an idiom for clustering a data series into n-length groups
311 using ``izip(*[iter(s)]*n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Christian Heimes1af737c2008-01-23 08:24:23 +0000313 :func:`izip` should only be used with unequal length inputs when you don't
314 care about trailing, unmatched values from the longer iterables. If those
315 values are important, use :func:`izip_longest` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317
318.. function:: izip_longest(*iterables[, fillvalue])
319
320 Make an iterator that aggregates elements from each of the iterables. If the
321 iterables are of uneven length, missing values are filled-in with *fillvalue*.
322 Iteration continues until the longest iterable is exhausted. Equivalent to::
323
324 def izip_longest(*args, **kwds):
325 fillvalue = kwds.get('fillvalue')
326 def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
327 yield counter() # yields the fillvalue, or raises IndexError
328 fillers = repeat(fillvalue)
329 iters = [chain(it, sentinel(), fillers) for it in args]
330 try:
331 for tup in izip(*iters):
332 yield tup
333 except IndexError:
334 pass
335
336 If one of the iterables is potentially infinite, then the :func:`izip_longest`
337 function should be wrapped with something that limits the number of calls (for
338 example :func:`islice` or :func:`takewhile`).
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Christian Heimes70e7ea22008-02-28 20:02:27 +0000341.. function:: permutations(iterable[, r])
342
343 Return successive *r* length permutations of elements in the *iterable*.
344
345 If *r* is not specified or is ``None``, then *r* defaults to the length
346 of the *iterable* and all possible full-length permutations
347 are generated.
348
349 Permutations are emitted in lexicographic sort order. So, if the
350 input *iterable* is sorted, the permutation tuples will be produced
351 in sorted order.
352
353 Elements are treated as unique based on their position, not on their
354 value. So if the input elements are unique, there will be no repeat
355 values in each permutation.
356
Christian Heimesb558a2e2008-03-02 22:46:37 +0000357 Equivalent to::
358
359 def permutations(iterable, r=None):
360 'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)'
361 pool = tuple(iterable)
362 n = len(pool)
363 r = n if r is None else r
364 indices = range(n)
365 cycles = range(n-r+1, n+1)[::-1]
366 yield tuple(pool[i] for i in indices[:r])
367 while n:
368 for i in reversed(range(r)):
369 cycles[i] -= 1
370 if cycles[i] == 0:
371 indices[i:] = indices[i+1:] + indices[i:i+1]
372 cycles[i] = n - i
373 else:
374 j = cycles[i]
375 indices[i], indices[-j] = indices[-j], indices[i]
376 yield tuple(pool[i] for i in indices[:r])
377 break
378 else:
379 return
Christian Heimes70e7ea22008-02-28 20:02:27 +0000380
381 .. versionadded:: 2.6
382
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000383.. function:: product(*iterables[, repeat])
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000384
385 Cartesian product of input iterables.
386
387 Equivalent to nested for-loops in a generator expression. For example,
388 ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.
389
390 The leftmost iterators are in the outermost for-loop, so the output tuples
391 cycle in a manner similar to an odometer (with the rightmost element
Christian Heimes836baa52008-02-26 08:18:30 +0000392 changing on every iteration). This results in a lexicographic ordering
393 so that if the inputs iterables are sorted, the product tuples are emitted
394 in sorted order.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000395
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000396 To compute the product of an iterable with itself, specify the number of
397 repetitions with the optional *repeat* keyword argument. For example,
398 ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``.
399
Christian Heimes836baa52008-02-26 08:18:30 +0000400 Equivalent to the following except that the actual implementation does not
401 build-up intermediate results in memory::
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000402
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000403 def product(*args, **kwds):
404 pools = map(tuple, args) * kwds.get('repeat', 1)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000405 if pools:
406 result = [[]]
407 for pool in pools:
408 result = [x+[y] for x in result for y in pool]
409 for prod in result:
410 yield tuple(prod)
411
412
Georg Brandl116aa622007-08-15 14:28:22 +0000413.. function:: repeat(object[, times])
414
415 Make an iterator that returns *object* over and over again. Runs indefinitely
416 unless the *times* argument is specified. Used as argument to :func:`imap` for
417 invariant parameters to the called function. Also used with :func:`izip` to
418 create an invariant part of a tuple record. Equivalent to::
419
420 def repeat(object, times=None):
421 if times is None:
422 while True:
423 yield object
424 else:
425 for i in range(times):
426 yield object
427
428
429.. function:: starmap(function, iterable)
430
Christian Heimes679db4a2008-01-18 09:56:22 +0000431 Make an iterator that computes the function using arguments obtained from
Georg Brandl116aa622007-08-15 14:28:22 +0000432 the iterable. Used instead of :func:`imap` when argument parameters are already
433 grouped in tuples from a single iterable (the data has been "pre-zipped"). The
434 difference between :func:`imap` and :func:`starmap` parallels the distinction
435 between ``function(a,b)`` and ``function(*c)``. Equivalent to::
436
437 def starmap(function, iterable):
Christian Heimes679db4a2008-01-18 09:56:22 +0000438 for args in iterable:
439 yield function(*args)
440
441 .. versionchanged:: 2.6
442 Previously, :func:`starmap` required the function arguments to be tuples.
443 Now, any iterable is allowed.
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445
446.. function:: takewhile(predicate, iterable)
447
448 Make an iterator that returns elements from the iterable as long as the
449 predicate is true. Equivalent to::
450
451 def takewhile(predicate, iterable):
452 for x in iterable:
453 if predicate(x):
454 yield x
455 else:
456 break
457
458
459.. function:: tee(iterable[, n=2])
460
461 Return *n* independent iterators from a single iterable. The case where ``n==2``
462 is equivalent to::
463
464 def tee(iterable):
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000465 def gen(next, data={}):
Georg Brandl116aa622007-08-15 14:28:22 +0000466 for i in count():
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000467 if i in data:
468 yield data.pop(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000469 else:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000470 data[i] = next()
471 yield data[i]
Georg Brandl116aa622007-08-15 14:28:22 +0000472 it = iter(iterable)
473 return (gen(it.__next__), gen(it.__next__))
474
475 Note, once :func:`tee` has made a split, the original *iterable* should not be
476 used anywhere else; otherwise, the *iterable* could get advanced without the tee
477 objects being informed.
478
479 Note, this member of the toolkit may require significant auxiliary storage
480 (depending on how much temporary data needs to be stored). In general, if one
481 iterator is going to use most or all of the data before the other iterator, it
482 is faster to use :func:`list` instead of :func:`tee`.
483
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485.. _itertools-example:
486
487Examples
488--------
489
490The following examples show common uses for each tool and demonstrate ways they
491can be combined. ::
492
493 >>> amounts = [120.15, 764.05, 823.14]
494 >>> for checknum, amount in izip(count(1200), amounts):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000495 ... print('Check %d is for $%.2f' % (checknum, amount))
Georg Brandl116aa622007-08-15 14:28:22 +0000496 ...
497 Check 1200 is for $120.15
498 Check 1201 is for $764.05
499 Check 1202 is for $823.14
500
501 >>> import operator
502 >>> for cube in imap(operator.pow, range(1,5), repeat(3)):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000503 ... print(cube)
Georg Brandl116aa622007-08-15 14:28:22 +0000504 ...
505 1
506 8
507 27
508 64
509
510 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
511 ... '', 'martin', '', 'walter', '', 'mark']
512 >>> for name in islice(reportlines, 3, None, 2):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000513 ... print(name.title())
Georg Brandl116aa622007-08-15 14:28:22 +0000514 ...
515 Alex
516 Laura
517 Martin
518 Walter
519 Mark
520
521 # Show a dictionary sorted and grouped by value
522 >>> from operator import itemgetter
523 >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Fred Drake2e748782007-09-04 17:33:11 +0000524 >>> di = sorted(d.items(), key=itemgetter(1))
Georg Brandl116aa622007-08-15 14:28:22 +0000525 >>> for k, g in groupby(di, key=itemgetter(1)):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000526 ... print(k, map(itemgetter(0), g))
Georg Brandl116aa622007-08-15 14:28:22 +0000527 ...
528 1 ['a', 'c', 'e']
529 2 ['b', 'd', 'f']
530 3 ['g']
531
532 # Find runs of consecutive numbers using groupby. The key to the solution
533 # is differencing with a range so that consecutive numbers all appear in
534 # same group.
535 >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
536 >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000537 ... print(map(operator.itemgetter(1), g))
Georg Brandl116aa622007-08-15 14:28:22 +0000538 ...
539 [1]
540 [4, 5, 6]
541 [10]
542 [15, 16, 17, 18]
543 [22]
544 [25, 26, 27, 28]
545
546
547
548.. _itertools-recipes:
549
550Recipes
551-------
552
553This section shows recipes for creating an extended toolset using the existing
554itertools as building blocks.
555
556The extended tools offer the same high performance as the underlying toolset.
557The superior memory performance is kept by processing elements one at a time
558rather than bringing the whole iterable into memory all at once. Code volume is
559kept small by linking the tools together in a functional style which helps
560eliminate temporary variables. High speed is retained by preferring
Georg Brandl9afde1c2007-11-01 20:32:30 +0000561"vectorized" building blocks over the use of for-loops and :term:`generator`\s
562which incur interpreter overhead. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000563
564 def take(n, seq):
565 return list(islice(seq, n))
566
567 def enumerate(iterable):
568 return izip(count(), iterable)
569
570 def tabulate(function):
571 "Return function(0), function(1), ..."
572 return imap(function, count())
573
Georg Brandl116aa622007-08-15 14:28:22 +0000574 def nth(iterable, n):
575 "Returns the nth item or raise StopIteration"
576 return islice(iterable, n, None).next()
577
578 def all(seq, pred=None):
579 "Returns True if pred(x) is true for every element in the iterable"
580 for elem in ifilterfalse(pred, seq):
581 return False
582 return True
583
584 def any(seq, pred=None):
585 "Returns True if pred(x) is true for at least one element in the iterable"
586 for elem in ifilter(pred, seq):
587 return True
588 return False
589
590 def no(seq, pred=None):
591 "Returns True if pred(x) is false for every element in the iterable"
592 for elem in ifilter(pred, seq):
593 return False
594 return True
595
596 def quantify(seq, pred=None):
597 "Count how many times the predicate is true in the sequence"
598 return sum(imap(pred, seq))
599
600 def padnone(seq):
601 """Returns the sequence elements and then returns None indefinitely.
602
603 Useful for emulating the behavior of the built-in map() function.
604 """
605 return chain(seq, repeat(None))
606
607 def ncycles(seq, n):
608 "Returns the sequence elements n times"
Christian Heimes70e7ea22008-02-28 20:02:27 +0000609 return chain.from_iterable(repeat(seq, n))
Georg Brandl116aa622007-08-15 14:28:22 +0000610
611 def dotproduct(vec1, vec2):
612 return sum(imap(operator.mul, vec1, vec2))
613
614 def flatten(listOfLists):
Christian Heimes70e7ea22008-02-28 20:02:27 +0000615 return list(chain.from_iterable(listOfLists))
Georg Brandl116aa622007-08-15 14:28:22 +0000616
617 def repeatfunc(func, times=None, *args):
618 """Repeat calls to func with specified arguments.
619
620 Example: repeatfunc(random.random)
621 """
622 if times is None:
623 return starmap(func, repeat(args))
Christian Heimes70e7ea22008-02-28 20:02:27 +0000624 return starmap(func, repeat(args, times))
Georg Brandl116aa622007-08-15 14:28:22 +0000625
626 def pairwise(iterable):
627 "s -> (s0,s1), (s1,s2), (s2, s3), ..."
628 a, b = tee(iterable)
629 next(b, None)
630 return izip(a, b)
631
632 def grouper(n, iterable, padvalue=None):
633 "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
634 return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
635
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000636 def roundrobin(*iterables):
637 "roundrobin('abc', 'd', 'ef') --> 'a', 'd', 'e', 'b', 'f', 'c'"
Christian Heimes70e7ea22008-02-28 20:02:27 +0000638 # Recipe credited to George Sakkis
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000639 pending = len(iterables)
640 nexts = cycle(iter(it).next for it in iterables)
641 while pending:
642 try:
643 for next in nexts:
644 yield next()
645 except StopIteration:
646 pending -= 1
647 nexts = cycle(islice(nexts, pending))
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000649 def powerset(iterable):
Christian Heimes70e7ea22008-02-28 20:02:27 +0000650 "powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])"
651 # Recipe credited to Eric Raymond
652 pairs = [(2**i, x) for i, x in enumerate(iterable)]
653 for n in xrange(2**len(pairs)):
654 yield set(x for m, x in pairs if m&n)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000655