Debian Codegraph @

cpython27/Lib/test/test_itertools.py

raw symbols SCIP
1 import unittest
2 from test import test_support
3 from itertools import *
4 import weakref
5 from decimal import Decimal
6 from fractions import Fraction
7 import sys
8 import operator
9 import random
10 import copy
11 import pickle
12 from functools import reduce
13 try:
14 import threading
15 except ImportError:
16 threading = None
17 maxsize = test_support.MAX_Py_ssize_t
18 minsize = -maxsize-1
19
20 def onearg(x):
21 'Test function of one argument'
22 return 2*x
23
24 def errfunc(*args):
25 'Test function that raises an error'
26 raise ValueError
27
28 def gen3():
29 'Non-restartable source sequence'
30 for i in (0, 1, 2):
31 yield i
32
33 def isEven(x):
34 'Test predicate'
35 return x%2==0
36
37 def isOdd(x):
38 'Test predicate'
39 return x%2==1
40
41 class StopNow:
42 'Class emulating an empty iterable.'
43 def __iter__(self):
44 return self
45 def next(self):
46 raise StopIteration
47
48 def take(n, seq):
49 'Convenience function for partially consuming a long of infinite iterable'
50 return list(islice(seq, n))
51
52 def prod(iterable):
53 return reduce(operator.mul, iterable, 1)
54
55 def fact(n):
56 'Factorial'
57 return prod(range(1, n+1))
58
59 class TestBasicOps(unittest.TestCase):
60 def test_chain(self):
61
62 def chain2(*iterables):
63 'Pure python version in the docs'
64 for it in iterables:
65 for element in it:
66 yield element
67
68 for c in (chain, chain2):
69 self.assertEqual(list(c('abc', 'def')), list('abcdef'))
70 self.assertEqual(list(c('abc')), list('abc'))
71 self.assertEqual(list(c('')), [])
72 self.assertEqual(take(4, c('abc', 'def')), list('abcd'))
73 self.assertRaises(TypeError, list,c(2, 3))
74
75 def test_chain_from_iterable(self):
76 self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef'))
77 self.assertEqual(list(chain.from_iterable(['abc'])), list('abc'))
78 self.assertEqual(list(chain.from_iterable([''])), [])
79 self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd'))
80 self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
81
82 def test_combinations(self):
83 self.assertRaises(TypeError, combinations, 'abc') # missing r argument
84 self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
85 self.assertRaises(TypeError, combinations, None) # pool is not iterable
86 self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
87 self.assertEqual(list(combinations('abc', 32)), []) # r > n
88 self.assertEqual(list(combinations(range(4), 3)),
89 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
90
91 def combinations1(iterable, r):
92 'Pure python version shown in the docs'
93 pool = tuple(iterable)
94 n = len(pool)
95 if r > n:
96 return
97 indices = range(r)
98 yield tuple(pool[i] for i in indices)
99 while 1:
100 for i in reversed(range(r)):
101 if indices[i] != i + n - r:
102 break
103 else:
104 return
105 indices[i] += 1
106 for j in range(i+1, r):
107 indices[j] = indices[j-1] + 1
108 yield tuple(pool[i] for i in indices)
109
110 def combinations2(iterable, r):
111 'Pure python version shown in the docs'
112 pool = tuple(iterable)
113 n = len(pool)
114 for indices in permutations(range(n), r):
115 if sorted(indices) == list(indices):
116 yield tuple(pool[i] for i in indices)
117
118 def combinations3(iterable, r):
119 'Pure python version from cwr()'
120 pool = tuple(iterable)
121 n = len(pool)
122 for indices in combinations_with_replacement(range(n), r):
123 if len(set(indices)) == r:
124 yield tuple(pool[i] for i in indices)
125
126 for n in range(7):
127 values = [5*x-12 for x in range(n)]
128 for r in range(n+2):
129 result = list(combinations(values, r))
130 self.assertEqual(len(result), 0 if r>n else fact(n) // fact(r) // fact(n-r)) # right number of combs
131 self.assertEqual(len(result), len(set(result))) # no repeats
132 self.assertEqual(result, sorted(result)) # lexicographic order
133 for c in result:
134 self.assertEqual(len(c), r) # r-length combinations
135 self.assertEqual(len(set(c)), r) # no duplicate elements
136 self.assertEqual(list(c), sorted(c)) # keep original ordering
137 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
138 self.assertEqual(list(c),
139 [e for e in values if e in c]) # comb is a subsequence of the input iterable
140 self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
141 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
142 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
143
144 @test_support.bigaddrspacetest
145 def test_combinations_overflow(self):
146 with self.assertRaises((OverflowError, MemoryError)):
147 combinations("AA", 2**29)
148
149 @test_support.impl_detail("tuple reuse is specific to CPython")
150 def test_combinations_tuple_reuse(self):
151 self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
152 self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
153
154 def test_combinations_with_replacement(self):
155 cwr = combinations_with_replacement
156 self.assertRaises(TypeError, cwr, 'abc') # missing r argument
157 self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments
158 self.assertRaises(TypeError, cwr, None) # pool is not iterable
159 self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative
160 self.assertEqual(list(cwr('ABC', 2)),
161 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
162
163 def cwr1(iterable, r):
164 'Pure python version shown in the docs'
165 # number items returned: (n+r-1)! / r! / (n-1)! when n>0
166 pool = tuple(iterable)
167 n = len(pool)
168 if not n and r:
169 return
170 indices = [0] * r
171 yield tuple(pool[i] for i in indices)
172 while 1:
173 for i in reversed(range(r)):
174 if indices[i] != n - 1:
175 break
176 else:
177 return
178 indices[i:] = [indices[i] + 1] * (r - i)
179 yield tuple(pool[i] for i in indices)
180
181 def cwr2(iterable, r):
182 'Pure python version shown in the docs'
183 pool = tuple(iterable)
184 n = len(pool)
185 for indices in product(range(n), repeat=r):
186 if sorted(indices) == list(indices):
187 yield tuple(pool[i] for i in indices)
188
189 def numcombs(n, r):
190 if not n:
191 return 0 if r else 1
192 return fact(n+r-1) // fact(r) // fact(n-1)
193
194 for n in range(7):
195 values = [5*x-12 for x in range(n)]
196 for r in range(n+2):
197 result = list(cwr(values, r))
198
199 self.assertEqual(len(result), numcombs(n, r)) # right number of combs
200 self.assertEqual(len(result), len(set(result))) # no repeats
201 self.assertEqual(result, sorted(result)) # lexicographic order
202
203 regular_combs = list(combinations(values, r)) # compare to combs without replacement
204 if n == 0 or r <= 1:
205 self.assertEqual(result, regular_combs) # cases that should be identical
206 else:
207 self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
208
209 for c in result:
210 self.assertEqual(len(c), r) # r-length combinations
211 noruns = [k for k,v in groupby(c)] # combo without consecutive repeats
212 self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive
213 self.assertEqual(list(c), sorted(c)) # keep original ordering
214 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
215 self.assertEqual(noruns,
216 [e for e in values if e in c]) # comb is a subsequence of the input iterable
217 self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version
218 self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version
219
220 @test_support.bigaddrspacetest
221 def test_combinations_with_replacement_overflow(self):
222 with self.assertRaises((OverflowError, MemoryError)):
223 combinations_with_replacement("AA", 2**30)
224
225 @test_support.impl_detail("tuple reuse is specific to CPython")
226 def test_combinations_with_replacement_tuple_reuse(self):
227 cwr = combinations_with_replacement
228 self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
229 self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
230
231 def test_permutations(self):
232 self.assertRaises(TypeError, permutations) # too few arguments
233 self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
234 self.assertRaises(TypeError, permutations, None) # pool is not iterable
235 self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
236 self.assertEqual(list(permutations('abc', 32)), []) # r > n
237 self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
238 self.assertEqual(list(permutations(range(3), 2)),
239 [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
240
241 def permutations1(iterable, r=None):
242 'Pure python version shown in the docs'
243 pool = tuple(iterable)
244 n = len(pool)
245 r = n if r is None else r
246 if r > n:
247 return
248 indices = range(n)
249 cycles = range(n, n-r, -1)
250 yield tuple(pool[i] for i in indices[:r])
251 while n:
252 for i in reversed(range(r)):
253 cycles[i] -= 1
254 if cycles[i] == 0:
255 indices[i:] = indices[i+1:] + indices[i:i+1]
256 cycles[i] = n - i
257 else:
258 j = cycles[i]
259 indices[i], indices[-j] = indices[-j], indices[i]
260 yield tuple(pool[i] for i in indices[:r])
261 break
262 else:
263 return
264
265 def permutations2(iterable, r=None):
266 'Pure python version shown in the docs'
267 pool = tuple(iterable)
268 n = len(pool)
269 r = n if r is None else r
270 for indices in product(range(n), repeat=r):
271 if len(set(indices)) == r:
272 yield tuple(pool[i] for i in indices)
273
274 for n in range(7):
275 values = [5*x-12 for x in range(n)]
276 for r in range(n+2):
277 result = list(permutations(values, r))
278 self.assertEqual(len(result), 0 if r>n else fact(n) // fact(n-r)) # right number of perms
279 self.assertEqual(len(result), len(set(result))) # no repeats
280 self.assertEqual(result, sorted(result)) # lexicographic order
281 for p in result:
282 self.assertEqual(len(p), r) # r-length permutations
283 self.assertEqual(len(set(p)), r) # no duplicate elements
284 self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
285 self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
286 self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
287 if r == n:
288 self.assertEqual(result, list(permutations(values, None))) # test r as None
289 self.assertEqual(result, list(permutations(values))) # test default r
290
291 @test_support.bigaddrspacetest
292 def test_permutations_overflow(self):
293 with self.assertRaises((OverflowError, MemoryError)):
294 permutations("A", 2**30)
295
296 @test_support.impl_detail("tuple reuse is specific to CPython")
297 def test_permutations_tuple_reuse(self):
298 self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
299 self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
300
301 def test_combinatorics(self):
302 # Test relationships between product(), permutations(),
303 # combinations() and combinations_with_replacement().
304
305 for n in range(6):
306 s = 'ABCDEFG'[:n]
307 for r in range(8):
308 prod = list(product(s, repeat=r))
309 cwr = list(combinations_with_replacement(s, r))
310 perm = list(permutations(s, r))
311 comb = list(combinations(s, r))
312
313 # Check size
314 self.assertEqual(len(prod), n**r)
315 self.assertEqual(len(cwr), (fact(n+r-1) // fact(r) // fact(n-1)) if n else (not r))
316 self.assertEqual(len(perm), 0 if r>n else fact(n) // fact(n-r))
317 self.assertEqual(len(comb), 0 if r>n else fact(n) // fact(r) // fact(n-r))
318
319 # Check lexicographic order without repeated tuples
320 self.assertEqual(prod, sorted(set(prod)))
321 self.assertEqual(cwr, sorted(set(cwr)))
322 self.assertEqual(perm, sorted(set(perm)))
323 self.assertEqual(comb, sorted(set(comb)))
324
325 # Check interrelationships
326 self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
327 self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups
328 self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted
329 self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups
330 self.assertEqual(comb, filter(set(cwr).__contains__, perm)) # comb: perm that is a cwr
331 self.assertEqual(comb, filter(set(perm).__contains__, cwr)) # comb: cwr that is a perm
332 self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm
333
334 def test_compress(self):
335 self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
336 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
337 self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list(''))
338 self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF'))
339 self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC'))
340 self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC'))
341 n = 10000
342 data = chain.from_iterable(repeat(range(6), n))
343 selectors = chain.from_iterable(repeat((0, 1)))
344 self.assertEqual(list(compress(data, selectors)), [1,3,5] * n)
345 self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable
346 self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable
347 self.assertRaises(TypeError, compress, range(6)) # too few args
348 self.assertRaises(TypeError, compress, range(6), None) # too many args
349
350 def test_count(self):
351 self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
352 self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
353 self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)])
354 self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
355 self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
356 self.assertRaises(TypeError, count, 2, 3, 4)
357 self.assertRaises(TypeError, count, 'a')
358 self.assertEqual(take(10, count(maxsize-5)), range(maxsize-5, maxsize+5))
359 self.assertEqual(take(10, count(-maxsize-5)), range(-maxsize-5, -maxsize+5))
360 self.assertEqual(take(3, count(3.25)), [3.25, 4.25, 5.25])
361 self.assertEqual(take(3, count(3.25-4j)), [3.25-4j, 4.25-4j, 5.25-4j])
362 self.assertEqual(take(3, count(Decimal('1.1'))),
363 [Decimal('1.1'), Decimal('2.1'), Decimal('3.1')])
364 self.assertEqual(take(3, count(Fraction(2, 3))),
365 [Fraction(2, 3), Fraction(5, 3), Fraction(8, 3)])
366 BIGINT = 1<<1000
367 self.assertEqual(take(3, count(BIGINT)), [BIGINT, BIGINT+1, BIGINT+2])
368 c = count(3)
369 self.assertEqual(repr(c), 'count(3)')
370 c.next()
371 self.assertEqual(repr(c), 'count(4)')
372 c = count(-9)
373 self.assertEqual(repr(c), 'count(-9)')
374 c.next()
375 self.assertEqual(next(c), -8)
376 self.assertEqual(repr(count(10.25)), 'count(10.25)')
377 self.assertEqual(repr(count(10.0)), 'count(10.0)')
378 self.assertEqual(type(next(count(10.0))), float)
379 for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
380 # Test repr (ignoring the L in longs)
381 r1 = repr(count(i)).replace('L', '')
382 r2 = 'count(%r)'.__mod__(i).replace('L', '')
383 self.assertEqual(r1, r2)
384
385 # check copy, deepcopy, pickle
386 for value in -3, 3, sys.maxint-5, sys.maxint+5:
387 c = count(value)
388 self.assertEqual(next(copy.copy(c)), value)
389 self.assertEqual(next(copy.deepcopy(c)), value)
390 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
391 self.assertEqual(next(pickle.loads(pickle.dumps(c, proto))), value)
392
393 def test_count_with_stride(self):
394 self.assertEqual(zip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
395 self.assertEqual(zip('abc',count(start=2,step=3)),
396 [('a', 2), ('b', 5), ('c', 8)])
397 self.assertEqual(zip('abc',count(step=-1)),
398 [('a', 0), ('b', -1), ('c', -2)])
399 self.assertRaises(TypeError, count, 'a', 'b')
400 self.assertEqual(zip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
401 self.assertEqual(zip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
402 self.assertEqual(zip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
403 self.assertEqual(zip('abc',count(2,1L)), [('a', 2), ('b', 3), ('c', 4)])
404 self.assertEqual(zip('abc',count(2,3L)), [('a', 2), ('b', 5), ('c', 8)])
405 self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
406 self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
407 self.assertEqual(take(3, count(10, maxsize+5)),
408 range(10, 10+3*(maxsize+5), maxsize+5))
409 self.assertEqual(take(3, count(2, 1.25)), [2, 3.25, 4.5])
410 self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
411 self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
412 [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
413 self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
414 [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
415 BIGINT = 1<<1000
416 self.assertEqual(take(3, count(step=BIGINT)), [0, BIGINT, 2*BIGINT])
417 self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
418 c = count(3, 5)
419 self.assertEqual(repr(c), 'count(3, 5)')
420 c.next()
421 self.assertEqual(repr(c), 'count(8, 5)')
422 c = count(-9, 0)
423 self.assertEqual(repr(c), 'count(-9, 0)')
424 c.next()
425 self.assertEqual(repr(c), 'count(-9, 0)')
426 c = count(-9, -3)
427 self.assertEqual(repr(c), 'count(-9, -3)')
428 c.next()
429 self.assertEqual(repr(c), 'count(-12, -3)')
430 self.assertEqual(repr(c), 'count(-12, -3)')
431 self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
432 self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int
433 self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0
434 self.assertEqual(repr(count(10, 1.00)), 'count(10, 1.0)')
435 c = count(10, 1.0)
436 self.assertEqual(type(next(c)), int)
437 self.assertEqual(type(next(c)), float)
438 for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
439 for j in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 1, 10, sys.maxint-5, sys.maxint+5):
440 # Test repr (ignoring the L in longs)
441 r1 = repr(count(i, j)).replace('L', '')
442 if j == 1:
443 r2 = ('count(%r)' % i).replace('L', '')
444 else:
445 r2 = ('count(%r, %r)' % (i, j)).replace('L', '')
446 self.assertEqual(r1, r2)
447
448 def test_cycle(self):
449 self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
450 self.assertEqual(list(cycle('')), [])
451 self.assertRaises(TypeError, cycle)
452 self.assertRaises(TypeError, cycle, 5)
453 self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
454
455 def test_groupby(self):
456 # Check whether it accepts arguments correctly
457 self.assertEqual([], list(groupby([])))
458 self.assertEqual([], list(groupby([], key=id)))
459 self.assertRaises(TypeError, list, groupby('abc', []))
460 self.assertRaises(TypeError, groupby, None)
461 self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
462
463 # Check normal input
464 s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
465 (2,15,22), (3,16,23), (3,17,23)]
466 dup = []
467 for k, g in groupby(s, lambda r:r[0]):
468 for elem in g:
469 self.assertEqual(k, elem[0])
470 dup.append(elem)
471 self.assertEqual(s, dup)
472
473 # Check nested case
474 dup = []
475 for k, g in groupby(s, lambda r:r[0]):
476 for ik, ig in groupby(g, lambda r:r[2]):
477 for elem in ig:
478 self.assertEqual(k, elem[0])
479 self.assertEqual(ik, elem[2])
480 dup.append(elem)
481 self.assertEqual(s, dup)
482
483 # Check case where inner iterator is not used
484 keys = [k for k, g in groupby(s, lambda r:r[0])]
485 expectedkeys = set([r[0] for r in s])
486 self.assertEqual(set(keys), expectedkeys)
487 self.assertEqual(len(keys), len(expectedkeys))
488
489 # Exercise pipes and filters style
490 s = 'abracadabra'
491 # sort s | uniq
492 r = [k for k, g in groupby(sorted(s))]
493 self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
494 # sort s | uniq -d
495 r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
496 self.assertEqual(r, ['a', 'b', 'r'])
497 # sort s | uniq -c
498 r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
499 self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
500 # sort s | uniq -c | sort -rn | head -3
501 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
502 self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
503
504 # iter.next failure
505 class ExpectedError(Exception):
506 pass
507 def delayed_raise(n=0):
508 for i in range(n):
509 yield 'yo'
510 raise ExpectedError
511 def gulp(iterable, keyp=None, func=list):
512 return [func(g) for k, g in groupby(iterable, keyp)]
513
514 # iter.next failure on outer object
515 self.assertRaises(ExpectedError, gulp, delayed_raise(0))
516 # iter.next failure on inner object
517 self.assertRaises(ExpectedError, gulp, delayed_raise(1))
518
519 # __cmp__ failure
520 class DummyCmp:
521 def __cmp__(self, dst):
522 raise ExpectedError
523 s = [DummyCmp(), DummyCmp(), None]
524
525 # __cmp__ failure on outer object
526 self.assertRaises(ExpectedError, gulp, s, func=id)
527 # __cmp__ failure on inner object
528 self.assertRaises(ExpectedError, gulp, s)
529
530 # keyfunc failure
531 def keyfunc(obj):
532 if keyfunc.skip > 0:
533 keyfunc.skip -= 1
534 return obj
535 else:
536 raise ExpectedError
537
538 # keyfunc failure on outer object
539 keyfunc.skip = 0
540 self.assertRaises(ExpectedError, gulp, [None], keyfunc)
541 keyfunc.skip = 1
542 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
543
544 def test_ifilter(self):
545 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
546 self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
547 self.assertEqual(list(ifilter(bool, [0,1,0,2,0])), [1,2])
548 self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6])
549 self.assertRaises(TypeError, ifilter)
550 self.assertRaises(TypeError, ifilter, lambda x:x)
551 self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
552 self.assertRaises(TypeError, ifilter, isEven, 3)
553 self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
554
555 def test_ifilterfalse(self):
556 self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
557 self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
558 self.assertEqual(list(ifilterfalse(bool, [0,1,0,2,0])), [0,0,0])
559 self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7])
560 self.assertRaises(TypeError, ifilterfalse)
561 self.assertRaises(TypeError, ifilterfalse, lambda x:x)
562 self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
563 self.assertRaises(TypeError, ifilterfalse, isEven, 3)
564 self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
565
566 def test_izip(self):
567 ans = [(x,y) for x, y in izip('abc',count())]
568 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
569 self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6)))
570 self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3)))
571 self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3)))
572 self.assertEqual(list(izip('abcdef')), zip('abcdef'))
573 self.assertEqual(list(izip()), zip())
574 self.assertRaises(TypeError, izip, 3)
575 self.assertRaises(TypeError, izip, range(3), 3)
576 self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
577 zip('abc', 'def'))
578 self.assertEqual([pair for pair in izip('abc', 'def')],
579 zip('abc', 'def'))
580
581 @test_support.impl_detail("tuple reuse is specific to CPython")
582 def test_izip_tuple_reuse(self):
583 ids = map(id, izip('abc', 'def'))
584 self.assertEqual(min(ids), max(ids))
585 ids = map(id, list(izip('abc', 'def')))
586 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
587
588 def test_iziplongest(self):
589 for args in [
590 ['abc', range(6)],
591 [range(6), 'abc'],
592 [range(1000), range(2000,2100), range(3000,3050)],
593 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
594 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
595 ]:
596 # target = map(None, *args) <- this raises a py3k warning
597 # this is the replacement:
598 target = [tuple([arg[i] if i < len(arg) else None for arg in args])
599 for i in range(max(map(len, args)))]
600 self.assertEqual(list(izip_longest(*args)), target)
601 self.assertEqual(list(izip_longest(*args, **{})), target)
602 target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
603 self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target)
604
605 self.assertEqual(take(3,izip_longest('abcdef', count())), zip('abcdef', range(3))) # take 3 from infinite input
606
607 self.assertEqual(list(izip_longest()), zip())
608 self.assertEqual(list(izip_longest([])), zip([]))
609 self.assertEqual(list(izip_longest('abcdef')), zip('abcdef'))
610
611 self.assertEqual(list(izip_longest('abc', 'defg', **{})),
612 zip(list('abc') + [None], 'defg')) # empty keyword dict
613 self.assertRaises(TypeError, izip_longest, 3)
614 self.assertRaises(TypeError, izip_longest, range(3), 3)
615
616 for stmt in [
617 "izip_longest('abc', fv=1)",
618 "izip_longest('abc', fillvalue=1, bogus_keyword=None)",
619 ]:
620 try:
621 eval(stmt, globals(), locals())
622 except TypeError:
623 pass
624 else:
625 self.fail('Did not raise Type in: ' + stmt)
626
627 self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')],
628 zip('abc', 'def'))
629 self.assertEqual([pair for pair in izip_longest('abc', 'def')],
630 zip('abc', 'def'))
631
632 @test_support.impl_detail("tuple reuse is specific to CPython")
633 def test_izip_longest_tuple_reuse(self):
634 ids = map(id, izip_longest('abc', 'def'))
635 self.assertEqual(min(ids), max(ids))
636 ids = map(id, list(izip_longest('abc', 'def')))
637 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
638
639 def test_bug_7244(self):
640
641 class Repeater(object):
642 # this class is similar to itertools.repeat
643 def __init__(self, o, t, e):
644 self.o = o
645 self.t = int(t)
646 self.e = e
647 def __iter__(self): # its iterator is itself
648 return self
649 def next(self):
650 if self.t > 0:
651 self.t -= 1
652 return self.o
653 else:
654 raise self.e
655
656 # Formerly this code in would fail in debug mode
657 # with Undetected Error and Stop Iteration
658 r1 = Repeater(1, 3, StopIteration)
659 r2 = Repeater(2, 4, StopIteration)
660 def run(r1, r2):
661 result = []
662 for i, j in izip_longest(r1, r2, fillvalue=0):
663 with test_support.captured_output('stdout'):
664 print (i, j)
665 result.append((i, j))
666 return result
667 self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])
668
669 # Formerly, the RuntimeError would be lost
670 # and StopIteration would stop as expected
671 r1 = Repeater(1, 3, RuntimeError)
672 r2 = Repeater(2, 4, StopIteration)
673 it = izip_longest(r1, r2, fillvalue=0)
674 self.assertEqual(next(it), (1, 2))
675 self.assertEqual(next(it), (1, 2))
676 self.assertEqual(next(it), (1, 2))
677 self.assertRaises(RuntimeError, next, it)
678
679 def test_product(self):
680 for args, result in [
681 ([], [()]), # zero iterables
682 (['ab'], [('a',), ('b',)]), # one iterable
683 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
684 ([range(0), range(2), range(3)], []), # first iterable with zero length
685 ([range(2), range(0), range(3)], []), # middle iterable with zero length
686 ([range(2), range(3), range(0)], []), # last iterable with zero length
687 ]:
688 self.assertEqual(list(product(*args)), result)
689 for r in range(4):
690 self.assertEqual(list(product(*(args*r))),
691 list(product(*args, **dict(repeat=r))))
692 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
693 self.assertRaises(TypeError, product, range(6), None)
694
695 def product1(*args, **kwds):
696 pools = map(tuple, args) * kwds.get('repeat', 1)
697 n = len(pools)
698 if n == 0:
699 yield ()
700 return
701 if any(len(pool) == 0 for pool in pools):
702 return
703 indices = [0] * n
704 yield tuple(pool[i] for pool, i in zip(pools, indices))
705 while 1:
706 for i in reversed(range(n)): # right to left
707 if indices[i] == len(pools[i]) - 1:
708 continue
709 indices[i] += 1
710 for j in range(i+1, n):
711 indices[j] = 0
712 yield tuple(pool[i] for pool, i in zip(pools, indices))
713 break
714 else:
715 return
716
717 def product2(*args, **kwds):
718 'Pure python version used in docs'
719 pools = map(tuple, args) * kwds.get('repeat', 1)
720 result = [[]]
721 for pool in pools:
722 result = [x+[y] for x in result for y in pool]
723 for prod in result:
724 yield tuple(prod)
725
726 argtypes = ['', 'abc', '', xrange(0), xrange(4), dict(a=1, b=2, c=3),
727 set('abcdefg'), range(11), tuple(range(13))]
728 for i in range(100):
729 args = [random.choice(argtypes) for j in range(random.randrange(5))]
730 expected_len = prod(map(len, args))
731 self.assertEqual(len(list(product(*args))), expected_len)
732 self.assertEqual(list(product(*args)), list(product1(*args)))
733 self.assertEqual(list(product(*args)), list(product2(*args)))
734 args = map(iter, args)
735 self.assertEqual(len(list(product(*args))), expected_len)
736
737 @test_support.bigaddrspacetest
738 def test_product_overflow(self):
739 with self.assertRaises((OverflowError, MemoryError)):
740 product(*(['ab']*2**5), repeat=2**25)
741
742 @test_support.impl_detail("tuple reuse is specific to CPython")
743 def test_product_tuple_reuse(self):
744 self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
745 self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
746
747 def test_repeat(self):
748 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
749 self.assertEqual(list(repeat(object='a', times=0)), [])
750 self.assertEqual(list(repeat(object='a', times=-1)), [])
751 self.assertEqual(list(repeat(object='a', times=-2)), [])
752 self.assertEqual(zip(xrange(3),repeat('a')),
753 [(0, 'a'), (1, 'a'), (2, 'a')])
754 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
755 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
756 self.assertEqual(list(repeat('a', 0)), [])
757 self.assertEqual(list(repeat('a', -3)), [])
758 self.assertRaises(TypeError, repeat)
759 self.assertRaises(TypeError, repeat, None, 3, 4)
760 self.assertRaises(TypeError, repeat, None, 'a')
761 r = repeat(1+0j)
762 self.assertEqual(repr(r), 'repeat((1+0j))')
763 r = repeat(1+0j, 5)
764 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
765 list(r)
766 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
767
768 def test_repeat_with_negative_times(self):
769 self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
770 self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
771 self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
772 self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
773
774 def test_imap(self):
775 self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
776 [0**1, 1**2, 2**3])
777 self.assertEqual(list(imap(None, 'abc', range(5))),
778 [('a',0),('b',1),('c',2)])
779 self.assertEqual(list(imap(None, 'abc', count())),
780 [('a',0),('b',1),('c',2)])
781 self.assertEqual(take(2,imap(None, 'abc', count())),
782 [('a',0),('b',1)])
783 self.assertEqual(list(imap(operator.pow, [])), [])
784 self.assertRaises(TypeError, imap)
785 self.assertRaises(TypeError, imap, operator.neg)
786 self.assertRaises(TypeError, imap(10, range(5)).next)
787 self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
788 self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
789
790 def test_starmap(self):
791 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
792 [0**1, 1**2, 2**3])
793 self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))),
794 [0**1, 1**2, 2**3])
795 self.assertEqual(list(starmap(operator.pow, [])), [])
796 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
797 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
798 self.assertRaises(TypeError, starmap)
799 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
800 self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
801 self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
802 self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
803
804 def test_islice(self):
805 for args in [ # islice(args) should agree with range(args)
806 (10, 20, 3),
807 (10, 3, 20),
808 (10, 20),
809 (10, 10),
810 (10, 3),
811 (20,)
812 ]:
813 self.assertEqual(list(islice(xrange(100), *args)), range(*args))
814
815 for args, tgtargs in [ # Stop when seqn is exhausted
816 ((10, 110, 3), ((10, 100, 3))),
817 ((10, 110), ((10, 100))),
818 ((110,), (100,))
819 ]:
820 self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
821
822 # Test stop=None
823 self.assertEqual(list(islice(xrange(10), None)), range(10))
824 self.assertEqual(list(islice(xrange(10), None, None)), range(10))
825 self.assertEqual(list(islice(xrange(10), None, None, None)), range(10))
826 self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
827 self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
828
829 # Test number of items consumed SF #1171417
830 it = iter(range(10))
831 self.assertEqual(list(islice(it, 3)), range(3))
832 self.assertEqual(list(it), range(3, 10))
833
834 it = iter(range(10))
835 self.assertEqual(list(islice(it, 3, 3)), [])
836 self.assertEqual(list(it), range(3, 10))
837
838 # Test invalid arguments
839 self.assertRaises(TypeError, islice, xrange(10))
840 self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
841 self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
842 self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
843 self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
844 self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
845 self.assertRaises(ValueError, islice, xrange(10), 'a')
846 self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
847 self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
848 self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
849 self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
850 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
851
852 # Issue #10323: Less islice in a predictable state
853 c = count()
854 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
855 self.assertEqual(next(c), 3)
856
857 # Issue #21321: check source iterator is not referenced
858 # from islice() after the latter has been exhausted
859 it = (x for x in (1, 2))
860 wr = weakref.ref(it)
861 it = islice(it, 1)
862 self.assertIsNotNone(wr())
863 list(it) # exhaust the iterator
864 test_support.gc_collect()
865 self.assertIsNone(wr())
866
867 def test_takewhile(self):
868 data = [1, 3, 5, 20, 2, 4, 6, 8]
869 underten = lambda x: x<10
870 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
871 self.assertEqual(list(takewhile(underten, [])), [])
872 self.assertRaises(TypeError, takewhile)
873 self.assertRaises(TypeError, takewhile, operator.pow)
874 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
875 self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
876 self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
877 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
878 self.assertEqual(list(t), [1, 1, 1])
879 self.assertRaises(StopIteration, t.next)
880
881 def test_dropwhile(self):
882 data = [1, 3, 5, 20, 2, 4, 6, 8]
883 underten = lambda x: x<10
884 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
885 self.assertEqual(list(dropwhile(underten, [])), [])
886 self.assertRaises(TypeError, dropwhile)
887 self.assertRaises(TypeError, dropwhile, operator.pow)
888 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
889 self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
890 self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
891
892 def test_tee(self):
893 n = 200
894 def irange(n):
895 for i in xrange(n):
896 yield i
897
898 a, b = tee([]) # test empty iterator
899 self.assertEqual(list(a), [])
900 self.assertEqual(list(b), [])
901
902 a, b = tee(irange(n)) # test 100% interleaved
903 self.assertEqual(zip(a,b), zip(range(n),range(n)))
904
905 a, b = tee(irange(n)) # test 0% interleaved
906 self.assertEqual(list(a), range(n))
907 self.assertEqual(list(b), range(n))
908
909 a, b = tee(irange(n)) # test dealloc of leading iterator
910 for i in xrange(100):
911 self.assertEqual(a.next(), i)
912 del a
913 self.assertEqual(list(b), range(n))
914
915 a, b = tee(irange(n)) # test dealloc of trailing iterator
916 for i in xrange(100):
917 self.assertEqual(a.next(), i)
918 del b
919 self.assertEqual(list(a), range(100, n))
920
921 for j in xrange(5): # test randomly interleaved
922 order = [0]*n + [1]*n
923 random.shuffle(order)
924 lists = ([], [])
925 its = tee(irange(n))
926 for i in order:
927 value = its[i].next()
928 lists[i].append(value)
929 self.assertEqual(lists[0], range(n))
930 self.assertEqual(lists[1], range(n))
931
932 # test argument format checking
933 self.assertRaises(TypeError, tee)
934 self.assertRaises(TypeError, tee, 3)
935 self.assertRaises(TypeError, tee, [1,2], 'x')
936 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
937
938 # tee object should be instantiable
939 a, b = tee('abc')
940 c = type(a)('def')
941 self.assertEqual(list(c), list('def'))
942
943 # test long-lagged and multi-way split
944 a, b, c = tee(xrange(2000), 3)
945 for i in xrange(100):
946 self.assertEqual(a.next(), i)
947 self.assertEqual(list(b), range(2000))
948 self.assertEqual([c.next(), c.next()], range(2))
949 self.assertEqual(list(a), range(100,2000))
950 self.assertEqual(list(c), range(2,2000))
951
952 # test values of n
953 self.assertRaises(TypeError, tee, 'abc', 'invalid')
954 self.assertRaises(ValueError, tee, [], -1)
955 for n in xrange(5):
956 result = tee('abc', n)
957 self.assertEqual(type(result), tuple)
958 self.assertEqual(len(result), n)
959 self.assertEqual(map(list, result), [list('abc')]*n)
960
961 # tee pass-through to copyable iterator
962 a, b = tee('abc')
963 c, d = tee(a)
964 self.assertTrue(a is c)
965
966 # test tee_new
967 t1, t2 = tee('abc')
968 tnew = type(t1)
969 self.assertRaises(TypeError, tnew)
970 self.assertRaises(TypeError, tnew, 10)
971 t3 = tnew(t1)
972 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
973
974 # test that tee objects are weak referencable
975 a, b = tee(xrange(10))
976 p = weakref.proxy(a)
977 self.assertEqual(getattr(p, '__class__'), type(b))
978 del a
979 self.assertRaises(ReferenceError, getattr, p, '__class__')
980
981 # Issue 13454: Crash when deleting backward iterator from tee()
982 def test_tee_del_backward(self):
983 forward, backward = tee(repeat(None, 20000000))
984 try:
985 any(forward) # exhaust the iterator
986 del backward
987 except:
988 del forward, backward
989 raise
990
991 def test_tee_reenter(self):
992 class I:
993 first = True
994 def __iter__(self):
995 return self
996 def next(self):
997 first = self.first
998 self.first = False
999 if first:
1000 return next(b)
1001
1002 a, b = tee(I())
1003 with self.assertRaisesRegexp(RuntimeError, "tee"):
1004 next(a)
1005
1006 @unittest.skipUnless(threading, 'Threading required for this test.')
1007 def test_tee_concurrent(self):
1008 start = threading.Event()
1009 finish = threading.Event()
1010 class I:
1011 def __iter__(self):
1012 return self
1013 def next(self):
1014 start.set()
1015 finish.wait()
1016
1017 a, b = tee(I())
1018 thread = threading.Thread(target=next, args=[a])
1019 thread.start()
1020 try:
1021 start.wait()
1022 with self.assertRaisesRegexp(RuntimeError, "tee"):
1023 next(b)
1024 finally:
1025 finish.set()
1026 thread.join()
1027
1028 def test_StopIteration(self):
1029 self.assertRaises(StopIteration, izip().next)
1030
1031 for f in (chain, cycle, izip, groupby):
1032 self.assertRaises(StopIteration, f([]).next)
1033 self.assertRaises(StopIteration, f(StopNow()).next)
1034
1035 self.assertRaises(StopIteration, islice([], None).next)
1036 self.assertRaises(StopIteration, islice(StopNow(), None).next)
1037
1038 p, q = tee([])
1039 self.assertRaises(StopIteration, p.next)
1040 self.assertRaises(StopIteration, q.next)
1041 p, q = tee(StopNow())
1042 self.assertRaises(StopIteration, p.next)
1043 self.assertRaises(StopIteration, q.next)
1044
1045 self.assertRaises(StopIteration, repeat(None, 0).next)
1046
1047 for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
1048 self.assertRaises(StopIteration, f(lambda x:x, []).next)
1049 self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
1050
1051 class TestExamples(unittest.TestCase):
1052
1053 def test_chain(self):
1054 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
1055
1056 def test_chain_from_iterable(self):
1057 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
1058
1059 def test_combinations(self):
1060 self.assertEqual(list(combinations('ABCD', 2)),
1061 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
1062 self.assertEqual(list(combinations(range(4), 3)),
1063 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
1064
1065 def test_combinations_with_replacement(self):
1066 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
1067 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
1068
1069 def test_compress(self):
1070 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
1071
1072 def test_count(self):
1073 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
1074
1075 def test_cycle(self):
1076 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
1077
1078 def test_dropwhile(self):
1079 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
1080
1081 def test_groupby(self):
1082 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
1083 list('ABCDAB'))
1084 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
1085 [list('AAAA'), list('BBB'), list('CC'), list('D')])
1086
1087 def test_ifilter(self):
1088 self.assertEqual(list(ifilter(lambda x: x%2, range(10))), [1,3,5,7,9])
1089
1090 def test_ifilterfalse(self):
1091 self.assertEqual(list(ifilterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
1092
1093 def test_imap(self):
1094 self.assertEqual(list(imap(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
1095
1096 def test_islice(self):
1097 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
1098 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
1099 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
1100 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1101
1102 def test_izip(self):
1103 self.assertEqual(list(izip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
1104
1105 def test_izip_longest(self):
1106 self.assertEqual(list(izip_longest('ABCD', 'xy', fillvalue='-')),
1107 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
1108
1109 def test_permutations(self):
1110 self.assertEqual(list(permutations('ABCD', 2)),
1111 map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split()))
1112 self.assertEqual(list(permutations(range(3))),
1113 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
1114
1115 def test_product(self):
1116 self.assertEqual(list(product('ABCD', 'xy')),
1117 map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split()))
1118 self.assertEqual(list(product(range(2), repeat=3)),
1119 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1120 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1121
1122 def test_repeat(self):
1123 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1124
1125 def test_stapmap(self):
1126 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1127 [32, 9, 1000])
1128
1129 def test_takewhile(self):
1130 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1131
1132
1133 class TestPurePythonRoughEquivalents(unittest.TestCase):
1134
1135 @staticmethod
1136 def islice(iterable, *args):
1137 s = slice(*args)
1138 start, stop, step = s.start or 0, s.stop or sys.maxint, s.step or 1
1139 it = iter(xrange(start, stop, step))
1140 try:
1141 nexti = next(it)
1142 except StopIteration:
1143 # Consume *iterable* up to the *start* position.
1144 for i, element in izip(xrange(start), iterable):
1145 pass
1146 return
1147 try:
1148 for i, element in enumerate(iterable):
1149 if i == nexti:
1150 yield element
1151 nexti = next(it)
1152 except StopIteration:
1153 # Consume to *stop*.
1154 for i, element in izip(xrange(i + 1, stop), iterable):
1155 pass
1156
1157 def test_islice_recipe(self):
1158 self.assertEqual(list(self.islice('ABCDEFG', 2)), list('AB'))
1159 self.assertEqual(list(self.islice('ABCDEFG', 2, 4)), list('CD'))
1160 self.assertEqual(list(self.islice('ABCDEFG', 2, None)), list('CDEFG'))
1161 self.assertEqual(list(self.islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1162 # Test items consumed.
1163 it = iter(xrange(10))
1164 self.assertEqual(list(self.islice(it, 3)), range(3))
1165 self.assertEqual(list(it), range(3, 10))
1166 it = iter(xrange(10))
1167 self.assertEqual(list(self.islice(it, 3, 3)), [])
1168 self.assertEqual(list(it), range(3, 10))
1169 # Test that slice finishes in predictable state.
1170 c = count()
1171 self.assertEqual(list(self.islice(c, 1, 3, 50)), [1])
1172 self.assertEqual(next(c), 3)
1173
1174
1175 class TestGC(unittest.TestCase):
1176
1177 def makecycle(self, iterator, container):
1178 container.append(iterator)
1179 iterator.next()
1180 del container, iterator
1181
1182 def test_chain(self):
1183 a = []
1184 self.makecycle(chain(a), a)
1185
1186 def test_chain_from_iterable(self):
1187 a = []
1188 self.makecycle(chain.from_iterable([a]), a)
1189
1190 def test_combinations(self):
1191 a = []
1192 self.makecycle(combinations([1,2,a,3], 3), a)
1193
1194 def test_combinations_with_replacement(self):
1195 a = []
1196 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1197
1198 def test_compress(self):
1199 a = []
1200 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1201
1202 def test_count(self):
1203 a = []
1204 Int = type('Int', (int,), dict(x=a))
1205 self.makecycle(count(Int(0), Int(1)), a)
1206
1207 def test_cycle(self):
1208 a = []
1209 self.makecycle(cycle([a]*2), a)
1210
1211 def test_dropwhile(self):
1212 a = []
1213 self.makecycle(dropwhile(bool, [0, a, a]), a)
1214
1215 def test_groupby(self):
1216 a = []
1217 self.makecycle(groupby([a]*2, lambda x:x), a)
1218
1219 def test_issue2246(self):
1220 # Issue 2246 -- the _grouper iterator was not included in GC
1221 n = 10
1222 keyfunc = lambda x: x
1223 for i, j in groupby(xrange(n), key=keyfunc):
1224 keyfunc.__dict__.setdefault('x',[]).append(j)
1225
1226 def test_ifilter(self):
1227 a = []
1228 self.makecycle(ifilter(lambda x:True, [a]*2), a)
1229
1230 def test_ifilterfalse(self):
1231 a = []
1232 self.makecycle(ifilterfalse(lambda x:False, a), a)
1233
1234 def test_izip(self):
1235 a = []
1236 self.makecycle(izip([a]*2, [a]*3), a)
1237
1238 def test_izip_longest(self):
1239 a = []
1240 self.makecycle(izip_longest([a]*2, [a]*3), a)
1241 b = [a, None]
1242 self.makecycle(izip_longest([a]*2, [a]*3, fillvalue=b), a)
1243
1244 def test_imap(self):
1245 a = []
1246 self.makecycle(imap(lambda x:x, [a]*2), a)
1247
1248 def test_islice(self):
1249 a = []
1250 self.makecycle(islice([a]*2, None), a)
1251
1252 def test_permutations(self):
1253 a = []
1254 self.makecycle(permutations([1,2,a,3], 3), a)
1255
1256 def test_product(self):
1257 a = []
1258 self.makecycle(product([1,2,a,3], repeat=3), a)
1259
1260 def test_repeat(self):
1261 a = []
1262 self.makecycle(repeat(a), a)
1263
1264 def test_starmap(self):
1265 a = []
1266 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1267
1268 def test_takewhile(self):
1269 a = []
1270 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1271
1272 def R(seqn):
1273 'Regular generator'
1274 for i in seqn:
1275 yield i
1276
1277 class G:
1278 'Sequence using __getitem__'
1279 def __init__(self, seqn):
1280 self.seqn = seqn
1281 def __getitem__(self, i):
1282 return self.seqn[i]
1283
1284 class I:
1285 'Sequence using iterator protocol'
1286 def __init__(self, seqn):
1287 self.seqn = seqn
1288 self.i = 0
1289 def __iter__(self):
1290 return self
1291 def next(self):
1292 if self.i >= len(self.seqn): raise StopIteration
1293 v = self.seqn[self.i]
1294 self.i += 1
1295 return v
1296
1297 class Ig:
1298 'Sequence using iterator protocol defined with a generator'
1299 def __init__(self, seqn):
1300 self.seqn = seqn
1301 self.i = 0
1302 def __iter__(self):
1303 for val in self.seqn:
1304 yield val
1305
1306 class X:
1307 'Missing __getitem__ and __iter__'
1308 def __init__(self, seqn):
1309 self.seqn = seqn
1310 self.i = 0
1311 def next(self):
1312 if self.i >= len(self.seqn): raise StopIteration
1313 v = self.seqn[self.i]
1314 self.i += 1
1315 return v
1316
1317 class N:
1318 'Iterator missing next()'
1319 def __init__(self, seqn):
1320 self.seqn = seqn
1321 self.i = 0
1322 def __iter__(self):
1323 return self
1324
1325 class E:
1326 'Test propagation of exceptions'
1327 def __init__(self, seqn):
1328 self.seqn = seqn
1329 self.i = 0
1330 def __iter__(self):
1331 return self
1332 def next(self):
1333 3 // 0
1334
1335 class S:
1336 'Test immediate stop'
1337 def __init__(self, seqn):
1338 pass
1339 def __iter__(self):
1340 return self
1341 def next(self):
1342 raise StopIteration
1343
1344 def L(seqn):
1345 'Test multiple tiers of iterators'
1346 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
1347
1348
1349 class TestVariousIteratorArgs(unittest.TestCase):
1350
1351 def test_chain(self):
1352 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1353 for g in (G, I, Ig, S, L, R):
1354 self.assertEqual(list(chain(g(s))), list(g(s)))
1355 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
1356 self.assertRaises(TypeError, list, chain(X(s)))
1357 self.assertRaises(TypeError, list, chain(N(s)))
1358 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
1359
1360 def test_compress(self):
1361 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1362 n = len(s)
1363 for g in (G, I, Ig, S, L, R):
1364 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
1365 self.assertRaises(TypeError, compress, X(s), repeat(1))
1366 self.assertRaises(TypeError, list, compress(N(s), repeat(1)))
1367 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
1368
1369 def test_product(self):
1370 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1371 self.assertRaises(TypeError, product, X(s))
1372 self.assertRaises(TypeError, product, N(s))
1373 self.assertRaises(ZeroDivisionError, product, E(s))
1374
1375 def test_cycle(self):
1376 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1377 for g in (G, I, Ig, S, L, R):
1378 tgtlen = len(s) * 3
1379 expected = list(g(s))*3
1380 actual = list(islice(cycle(g(s)), tgtlen))
1381 self.assertEqual(actual, expected)
1382 self.assertRaises(TypeError, cycle, X(s))
1383 self.assertRaises(TypeError, list, cycle(N(s)))
1384 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
1385
1386 def test_groupby(self):
1387 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1388 for g in (G, I, Ig, S, L, R):
1389 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
1390 self.assertRaises(TypeError, groupby, X(s))
1391 self.assertRaises(TypeError, list, groupby(N(s)))
1392 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
1393
1394 def test_ifilter(self):
1395 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1396 for g in (G, I, Ig, S, L, R):
1397 self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
1398 self.assertRaises(TypeError, ifilter, isEven, X(s))
1399 self.assertRaises(TypeError, list, ifilter(isEven, N(s)))
1400 self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
1401
1402 def test_ifilterfalse(self):
1403 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1404 for g in (G, I, Ig, S, L, R):
1405 self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
1406 self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
1407 self.assertRaises(TypeError, list, ifilterfalse(isEven, N(s)))
1408 self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
1409
1410 def test_izip(self):
1411 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1412 for g in (G, I, Ig, S, L, R):
1413 self.assertEqual(list(izip(g(s))), zip(g(s)))
1414 self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s)))
1415 self.assertRaises(TypeError, izip, X(s))
1416 self.assertRaises(TypeError, list, izip(N(s)))
1417 self.assertRaises(ZeroDivisionError, list, izip(E(s)))
1418
1419 def test_iziplongest(self):
1420 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1421 for g in (G, I, Ig, S, L, R):
1422 self.assertEqual(list(izip_longest(g(s))), zip(g(s)))
1423 self.assertEqual(list(izip_longest(g(s), g(s))), zip(g(s), g(s)))
1424 self.assertRaises(TypeError, izip_longest, X(s))
1425 self.assertRaises(TypeError, list, izip_longest(N(s)))
1426 self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
1427
1428 def test_imap(self):
1429 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1430 for g in (G, I, Ig, S, L, R):
1431 self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
1432 self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
1433 self.assertRaises(TypeError, imap, onearg, X(s))
1434 self.assertRaises(TypeError, list, imap(onearg, N(s)))
1435 self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
1436
1437 def test_islice(self):
1438 for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1439 for g in (G, I, Ig, S, L, R):
1440 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
1441 self.assertRaises(TypeError, islice, X(s), 10)
1442 self.assertRaises(TypeError, list, islice(N(s), 10))
1443 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
1444
1445 def test_starmap(self):
1446 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1447 for g in (G, I, Ig, S, L, R):
1448 ss = zip(s, s)
1449 self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
1450 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
1451 self.assertRaises(TypeError, list, starmap(operator.pow, N(ss)))
1452 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
1453
1454 def test_takewhile(self):
1455 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1456 for g in (G, I, Ig, S, L, R):
1457 tgt = []
1458 for elem in g(s):
1459 if not isEven(elem): break
1460 tgt.append(elem)
1461 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
1462 self.assertRaises(TypeError, takewhile, isEven, X(s))
1463 self.assertRaises(TypeError, list, takewhile(isEven, N(s)))
1464 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
1465
1466 def test_dropwhile(self):
1467 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1468 for g in (G, I, Ig, S, L, R):
1469 tgt = []
1470 for elem in g(s):
1471 if not tgt and isOdd(elem): continue
1472 tgt.append(elem)
1473 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
1474 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
1475 self.assertRaises(TypeError, list, dropwhile(isOdd, N(s)))
1476 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
1477
1478 def test_tee(self):
1479 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1480 for g in (G, I, Ig, S, L, R):
1481 it1, it2 = tee(g(s))
1482 self.assertEqual(list(it1), list(g(s)))
1483 self.assertEqual(list(it2), list(g(s)))
1484 self.assertRaises(TypeError, tee, X(s))
1485 self.assertRaises(TypeError, list, tee(N(s))[0])
1486 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
1487
1488 class LengthTransparency(unittest.TestCase):
1489
1490 def test_repeat(self):
1491 from test.test_iterlen import len
1492 self.assertEqual(len(repeat(None, 50)), 50)
1493 self.assertRaises(TypeError, len, repeat(None))
1494
1495 class RegressionTests(unittest.TestCase):
1496
1497 def test_sf_793826(self):
1498 # Fix Armin Rigo's successful efforts to wreak havoc
1499
1500 def mutatingtuple(tuple1, f, tuple2):
1501 # this builds a tuple t which is a copy of tuple1,
1502 # then calls f(t), then mutates t to be equal to tuple2
1503 # (needs len(tuple1) == len(tuple2)).
1504 def g(value, first=[1]):
1505 if first:
1506 del first[:]
1507 f(z.next())
1508 return value
1509 items = list(tuple2)
1510 items[1:1] = list(tuple1)
1511 gen = imap(g, items)
1512 z = izip(*[gen]*len(tuple1))
1513 z.next()
1514
1515 def f(t):
1516 global T
1517 T = t
1518 first[:] = list(T)
1519
1520 first = []
1521 mutatingtuple((1,2,3), f, (4,5,6))
1522 second = list(T)
1523 self.assertEqual(first, second)
1524
1525
1526 def test_sf_950057(self):
1527 # Make sure that chain() and cycle() catch exceptions immediately
1528 # rather than when shifting between input sources
1529
1530 def gen1():
1531 hist.append(0)
1532 yield 1
1533 hist.append(1)
1534 raise AssertionError
1535 hist.append(2)
1536
1537 def gen2(x):
1538 hist.append(3)
1539 yield 2
1540 hist.append(4)
1541 if x:
1542 raise StopIteration
1543
1544 hist = []
1545 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
1546 self.assertEqual(hist, [0,1])
1547
1548 hist = []
1549 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
1550 self.assertEqual(hist, [0,1])
1551
1552 hist = []
1553 self.assertRaises(AssertionError, list, cycle(gen1()))
1554 self.assertEqual(hist, [0,1])
1555
1556 def test_long_chain_of_empty_iterables(self):
1557 # Make sure itertools.chain doesn't run into recursion limits when
1558 # dealing with long chains of empty iterables. Even with a high
1559 # number this would probably only fail in Py_DEBUG mode.
1560 it = chain.from_iterable(() for unused in xrange(10000000))
1561 with self.assertRaises(StopIteration):
1562 next(it)
1563
1564 def test_issue30347_1(self):
1565 def f(n):
1566 if n == 5:
1567 list(b)
1568 return n != 6
1569 for (k, b) in groupby(range(10), f):
1570 list(b) # shouldn't crash
1571
1572 def test_issue30347_2(self):
1573 class K(object):
1574 i = 0
1575 def __init__(self, v):
1576 pass
1577 def __eq__(self, other):
1578 K.i += 1
1579 if K.i == 1:
1580 next(g, None)
1581 return True
1582 def __hash__(self):
1583 return 1
1584 g = next(groupby(range(10), K))[1]
1585 for j in range(2):
1586 next(g, None) # shouldn't crash
1587
1588
1589 class SubclassWithKwargsTest(unittest.TestCase):
1590 def test_keywords_in_subclass(self):
1591 # count is not subclassable...
1592 for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap,
1593 starmap, islice, takewhile, dropwhile, cycle, compress):
1594 class Subclass(cls):
1595 def __init__(self, newarg=None, *args):
1596 cls.__init__(self, *args)
1597 try:
1598 Subclass(newarg=1)
1599 except TypeError, err:
1600 # we expect type errors because of wrong argument count
1601 self.assertNotIn("does not take keyword arguments", err.args[0])
1602
1603
1604 libreftest = """ Doctest for examples in the library reference: libitertools.tex
1605
1606
1607 >>> amounts = [120.15, 764.05, 823.14]
1608 >>> for checknum, amount in izip(count(1200), amounts):
1609 ... print 'Check %d is for $%.2f' % (checknum, amount)
1610 ...
1611 Check 1200 is for $120.15
1612 Check 1201 is for $764.05
1613 Check 1202 is for $823.14
1614
1615 >>> import operator
1616 >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
1617 ... print cube
1618 ...
1619 1
1620 8
1621 27
1622
1623 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
1624 >>> for name in islice(reportlines, 3, None, 2):
1625 ... print name.title()
1626 ...
1627 Alex
1628 Laura
1629 Martin
1630 Walter
1631 Samuele
1632
1633 >>> from operator import itemgetter
1634 >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
1635 >>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
1636 >>> for k, g in groupby(di, itemgetter(1)):
1637 ... print k, map(itemgetter(0), g)
1638 ...
1639 1 ['a', 'c', 'e']
1640 2 ['b', 'd', 'f']
1641 3 ['g']
1642
1643 # Find runs of consecutive numbers using groupby. The key to the solution
1644 # is differencing with a range so that consecutive numbers all appear in
1645 # same group.
1646 >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
1647 >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
1648 ... print map(operator.itemgetter(1), g)
1649 ...
1650 [1]
1651 [4, 5, 6]
1652 [10]
1653 [15, 16, 17, 18]
1654 [22]
1655 [25, 26, 27, 28]
1656
1657 >>> def take(n, iterable):
1658 ... "Return first n items of the iterable as a list"
1659 ... return list(islice(iterable, n))
1660
1661 >>> def enumerate(iterable, start=0):
1662 ... return izip(count(start), iterable)
1663
1664 >>> def tabulate(function, start=0):
1665 ... "Return function(0), function(1), ..."
1666 ... return imap(function, count(start))
1667
1668 >>> import collections
1669 >>> def consume(iterator, n=None):
1670 ... "Advance the iterator n-steps ahead. If n is None, consume entirely."
1671 ... # Use functions that consume iterators at C speed.
1672 ... if n is None:
1673 ... # feed the entire iterator into a zero-length deque
1674 ... collections.deque(iterator, maxlen=0)
1675 ... else:
1676 ... # advance to the empty slice starting at position n
1677 ... next(islice(iterator, n, n), None)
1678
1679 >>> def nth(iterable, n, default=None):
1680 ... "Returns the nth item or a default value"
1681 ... return next(islice(iterable, n, None), default)
1682
1683 >>> def all_equal(iterable):
1684 ... "Returns True if all the elements are equal to each other"
1685 ... g = groupby(iterable)
1686 ... return next(g, True) and not next(g, False)
1687
1688 >>> def quantify(iterable, pred=bool):
1689 ... "Count how many times the predicate is true"
1690 ... return sum(imap(pred, iterable))
1691
1692 >>> def padnone(iterable):
1693 ... "Returns the sequence elements and then returns None indefinitely"
1694 ... return chain(iterable, repeat(None))
1695
1696 >>> def ncycles(iterable, n):
1697 ... "Returns the sequence elements n times"
1698 ... return chain(*repeat(iterable, n))
1699
1700 >>> def dotproduct(vec1, vec2):
1701 ... return sum(imap(operator.mul, vec1, vec2))
1702
1703 >>> def flatten(listOfLists):
1704 ... return list(chain.from_iterable(listOfLists))
1705
1706 >>> def repeatfunc(func, times=None, *args):
1707 ... "Repeat calls to func with specified arguments."
1708 ... " Example: repeatfunc(random.random)"
1709 ... if times is None:
1710 ... return starmap(func, repeat(args))
1711 ... else:
1712 ... return starmap(func, repeat(args, times))
1713
1714 >>> def pairwise(iterable):
1715 ... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1716 ... a, b = tee(iterable)
1717 ... for elem in b:
1718 ... break
1719 ... return izip(a, b)
1720
1721 >>> def grouper(n, iterable, fillvalue=None):
1722 ... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
1723 ... args = [iter(iterable)] * n
1724 ... return izip_longest(fillvalue=fillvalue, *args)
1725
1726 >>> def roundrobin(*iterables):
1727 ... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
1728 ... # Recipe credited to George Sakkis
1729 ... pending = len(iterables)
1730 ... nexts = cycle(iter(it).next for it in iterables)
1731 ... while pending:
1732 ... try:
1733 ... for next in nexts:
1734 ... yield next()
1735 ... except StopIteration:
1736 ... pending -= 1
1737 ... nexts = cycle(islice(nexts, pending))
1738
1739 >>> def powerset(iterable):
1740 ... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
1741 ... s = list(iterable)
1742 ... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
1743
1744 >>> def unique_everseen(iterable, key=None):
1745 ... "List unique elements, preserving order. Remember all elements ever seen."
1746 ... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
1747 ... # unique_everseen('ABBCcAD', str.lower) --> A B C D
1748 ... seen = set()
1749 ... seen_add = seen.add
1750 ... if key is None:
1751 ... for element in iterable:
1752 ... if element not in seen:
1753 ... seen_add(element)
1754 ... yield element
1755 ... else:
1756 ... for element in iterable:
1757 ... k = key(element)
1758 ... if k not in seen:
1759 ... seen_add(k)
1760 ... yield element
1761
1762 >>> def unique_justseen(iterable, key=None):
1763 ... "List unique elements, preserving order. Remember only the element just seen."
1764 ... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
1765 ... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
1766 ... return imap(next, imap(itemgetter(1), groupby(iterable, key)))
1767
1768 This is not part of the examples but it tests to make sure the definitions
1769 perform as purported.
1770
1771 >>> take(10, count())
1772 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1773
1774 >>> list(enumerate('abc'))
1775 [(0, 'a'), (1, 'b'), (2, 'c')]
1776
1777 >>> list(islice(tabulate(lambda x: 2*x), 4))
1778 [0, 2, 4, 6]
1779
1780 >>> it = iter(xrange(10))
1781 >>> consume(it, 3)
1782 >>> next(it)
1783 3
1784 >>> consume(it)
1785 >>> next(it, 'Done')
1786 'Done'
1787
1788 >>> nth('abcde', 3)
1789 'd'
1790
1791 >>> nth('abcde', 9) is None
1792 True
1793
1794 >>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
1795 [True, True, True, False, False]
1796
1797 >>> quantify(xrange(99), lambda x: x%2==0)
1798 50
1799
1800 >>> a = [[1, 2, 3], [4, 5, 6]]
1801 >>> flatten(a)
1802 [1, 2, 3, 4, 5, 6]
1803
1804 >>> list(repeatfunc(pow, 5, 2, 3))
1805 [8, 8, 8, 8, 8]
1806
1807 >>> import random
1808 >>> take(5, imap(int, repeatfunc(random.random)))
1809 [0, 0, 0, 0, 0]
1810
1811 >>> list(pairwise('abcd'))
1812 [('a', 'b'), ('b', 'c'), ('c', 'd')]
1813
1814 >>> list(pairwise([]))
1815 []
1816
1817 >>> list(pairwise('a'))
1818 []
1819
1820 >>> list(islice(padnone('abc'), 0, 6))
1821 ['a', 'b', 'c', None, None, None]
1822
1823 >>> list(ncycles('abc', 3))
1824 ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
1825
1826 >>> dotproduct([1,2,3], [4,5,6])
1827 32
1828
1829 >>> list(grouper(3, 'abcdefg', 'x'))
1830 [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
1831
1832 >>> list(roundrobin('abc', 'd', 'ef'))
1833 ['a', 'd', 'e', 'b', 'f', 'c']
1834
1835 >>> list(powerset([1,2,3]))
1836 [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
1837
1838 >>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
1839 True
1840
1841 >>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
1842 True
1843
1844 >>> list(unique_everseen('AAAABBBCCDAABBB'))
1845 ['A', 'B', 'C', 'D']
1846
1847 >>> list(unique_everseen('ABBCcAD', str.lower))
1848 ['A', 'B', 'C', 'D']
1849
1850 >>> list(unique_justseen('AAAABBBCCDAABBB'))
1851 ['A', 'B', 'C', 'D', 'A', 'B']
1852
1853 >>> list(unique_justseen('ABBCcAD', str.lower))
1854 ['A', 'B', 'C', 'A', 'D']
1855
1856 """
1857
1858 __test__ = {'libreftest' : libreftest}
1859
1860 def test_main(verbose=None):
1861 test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
1862 RegressionTests, LengthTransparency,
1863 SubclassWithKwargsTest, TestExamples,
1864 TestPurePythonRoughEquivalents)
1865 test_support.run_unittest(*test_classes)
1866
1867 # verify reference counting
1868 if verbose and hasattr(sys, "gettotalrefcount"):
1869 import gc
1870 counts = [None] * 5
1871 for i in xrange(len(counts)):
1872 test_support.run_unittest(*test_classes)
1873 gc.collect()
1874 counts[i] = sys.gettotalrefcount()
1875 print counts
1876
1877 # doctest the examples in the library reference
1878 test_support.run_doctest(sys.modules[__name__], verbose)
1879
1880 if __name__ == "__main__":
1881 test_main(verbose=True)