source: python/trunk/Lib/test/test_itertools.py

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

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