blob: 3c7dd499952b88cc9206cc1396d4cbbdc6379f94 [file] [log] [blame]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001import unittest
2from test import test_support
3from itertools import *
Antoine Pitrou3ec903f2014-04-29 12:13:46 +02004import weakref
Raymond Hettingeraa044612009-02-12 12:04:26 +00005from decimal import Decimal
Raymond Hettingerdbe3bfb2009-02-12 12:43:01 +00006from fractions import Fraction
Raymond Hettinger2012f172003-02-07 05:32:58 +00007import sys
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00008import operator
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00009import random
Raymond Hettingere09f45a2009-11-30 19:44:40 +000010import copy
11import pickle
Ezio Melottidde5b942010-02-03 05:37:26 +000012from functools import reduce
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +000013maxsize = test_support.MAX_Py_ssize_t
14minsize = -maxsize-1
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000015
16def onearg(x):
17 'Test function of one argument'
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000018 return 2*x
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000019
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
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000033def isOdd(x):
34 'Test predicate'
35 return x%2==1
36
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000037class StopNow:
38 'Class emulating an empty iterable.'
39 def __iter__(self):
40 return self
41 def next(self):
42 raise StopIteration
Raymond Hettinger96ef8112003-02-01 00:10:11 +000043
Raymond Hettinger02420702003-06-29 20:36:23 +000044def take(n, seq):
45 'Convenience function for partially consuming a long of infinite iterable'
46 return list(islice(seq, n))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000047
Raymond Hettingerd553d852008-03-04 04:17:08 +000048def prod(iterable):
49 return reduce(operator.mul, iterable, 1)
50
Raymond Hettinger93e804d2008-02-26 23:40:50 +000051def fact(n):
52 'Factorial'
Raymond Hettingerd553d852008-03-04 04:17:08 +000053 return prod(range(1, n+1))
54
Raymond Hettinger96ef8112003-02-01 00:10:11 +000055class TestBasicOps(unittest.TestCase):
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000056 def test_chain(self):
Raymond Hettingerad47fa12008-03-06 20:52:01 +000057
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))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000070
Raymond Hettingerb4cbc982008-02-28 22:46:41 +000071 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
Raymond Hettinger93e804d2008-02-26 23:40:50 +000078 def test_combinations(self):
Raymond Hettinger5b913e32009-01-08 06:39:04 +000079 self.assertRaises(TypeError, combinations, 'abc') # missing r argument
Raymond Hettinger93e804d2008-02-26 23:40:50 +000080 self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
Raymond Hettingerd553d852008-03-04 04:17:08 +000081 self.assertRaises(TypeError, combinations, None) # pool is not iterable
Raymond Hettinger93e804d2008-02-26 23:40:50 +000082 self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
Raymond Hettinger5b913e32009-01-08 06:39:04 +000083 self.assertEqual(list(combinations('abc', 32)), []) # r > n
Raymond Hettinger93e804d2008-02-26 23:40:50 +000084 self.assertEqual(list(combinations(range(4), 3)),
85 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
Raymond Hettingerd553d852008-03-04 04:17:08 +000086
87 def combinations1(iterable, r):
88 'Pure python version shown in the docs'
89 pool = tuple(iterable)
90 n = len(pool)
Raymond Hettinger5b913e32009-01-08 06:39:04 +000091 if r > n:
92 return
Raymond Hettingerd553d852008-03-04 04:17:08 +000093 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
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000114 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
Raymond Hettingerd553d852008-03-04 04:17:08 +0000122 for n in range(7):
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000123 values = [5*x-12 for x in range(n)]
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000124 for r in range(n+2):
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000125 result = list(combinations(values, r))
Ezio Melottidde5b942010-02-03 05:37:26 +0000126 self.assertEqual(len(result), 0 if r>n else fact(n) // fact(r) // fact(n-r)) # right number of combs
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000127 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
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000133 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000134 self.assertEqual(list(c),
135 [e for e in values if e in c]) # comb is a subsequence of the input iterable
Raymond Hettingerd553d852008-03-04 04:17:08 +0000136 self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000137 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000138 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
Raymond Hettingerd553d852008-03-04 04:17:08 +0000139
Benjamin Peterson021dec12015-02-01 20:59:00 -0500140 @test_support.bigaddrspacetest
141 def test_combinations_overflow(self):
142 with self.assertRaises(OverflowError):
143 combinations("AA", 2**29)
144
Alex Gaynor97376482011-07-17 16:44:31 -0700145 @test_support.impl_detail("tuple reuse is specific to CPython")
146 def test_combinations_tuple_reuse(self):
Raymond Hettingerd553d852008-03-04 04:17:08 +0000147 self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
148 self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
149
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000150 def test_combinations_with_replacement(self):
151 cwr = combinations_with_replacement
152 self.assertRaises(TypeError, cwr, 'abc') # missing r argument
153 self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments
154 self.assertRaises(TypeError, cwr, None) # pool is not iterable
155 self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative
156 self.assertEqual(list(cwr('ABC', 2)),
157 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
158
159 def cwr1(iterable, r):
160 'Pure python version shown in the docs'
161 # number items returned: (n+r-1)! / r! / (n-1)! when n>0
162 pool = tuple(iterable)
163 n = len(pool)
164 if not n and r:
165 return
166 indices = [0] * r
167 yield tuple(pool[i] for i in indices)
168 while 1:
169 for i in reversed(range(r)):
170 if indices[i] != n - 1:
171 break
172 else:
173 return
174 indices[i:] = [indices[i] + 1] * (r - i)
175 yield tuple(pool[i] for i in indices)
176
177 def cwr2(iterable, r):
178 'Pure python version shown in the docs'
179 pool = tuple(iterable)
180 n = len(pool)
181 for indices in product(range(n), repeat=r):
182 if sorted(indices) == list(indices):
183 yield tuple(pool[i] for i in indices)
184
185 def numcombs(n, r):
186 if not n:
187 return 0 if r else 1
Ezio Melottidde5b942010-02-03 05:37:26 +0000188 return fact(n+r-1) // fact(r) // fact(n-1)
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000189
190 for n in range(7):
191 values = [5*x-12 for x in range(n)]
192 for r in range(n+2):
193 result = list(cwr(values, r))
194
195 self.assertEqual(len(result), numcombs(n, r)) # right number of combs
196 self.assertEqual(len(result), len(set(result))) # no repeats
197 self.assertEqual(result, sorted(result)) # lexicographic order
198
199 regular_combs = list(combinations(values, r)) # compare to combs without replacement
200 if n == 0 or r <= 1:
Ezio Melotti2623a372010-11-21 13:34:58 +0000201 self.assertEqual(result, regular_combs) # cases that should be identical
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000202 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000203 self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000204
205 for c in result:
206 self.assertEqual(len(c), r) # r-length combinations
207 noruns = [k for k,v in groupby(c)] # combo without consecutive repeats
208 self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive
209 self.assertEqual(list(c), sorted(c)) # keep original ordering
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000210 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000211 self.assertEqual(noruns,
212 [e for e in values if e in c]) # comb is a subsequence of the input iterable
213 self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version
214 self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version
215
Benjamin Peterson17845c12015-02-01 21:10:47 -0500216 @test_support.bigaddrspacetest
217 def test_combinations_with_replacement_overflow(self):
218 with self.assertRaises(OverflowError):
219 combinations_with_replacement("AA", 2**30)
220
Alex Gaynor97376482011-07-17 16:44:31 -0700221 @test_support.impl_detail("tuple reuse is specific to CPython")
222 def test_combinations_with_replacement_tuple_reuse(self):
223 cwr = combinations_with_replacement
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000224 self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
225 self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
226
Raymond Hettingerd553d852008-03-04 04:17:08 +0000227 def test_permutations(self):
228 self.assertRaises(TypeError, permutations) # too few arguments
229 self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000230 self.assertRaises(TypeError, permutations, None) # pool is not iterable
231 self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000232 self.assertEqual(list(permutations('abc', 32)), []) # r > n
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000233 self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
Raymond Hettingerd553d852008-03-04 04:17:08 +0000234 self.assertEqual(list(permutations(range(3), 2)),
235 [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
236
237 def permutations1(iterable, r=None):
238 'Pure python version shown in the docs'
239 pool = tuple(iterable)
240 n = len(pool)
241 r = n if r is None else r
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000242 if r > n:
243 return
Raymond Hettingerd553d852008-03-04 04:17:08 +0000244 indices = range(n)
Raymond Hettingere70bb8d2008-03-23 00:55:46 +0000245 cycles = range(n, n-r, -1)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000246 yield tuple(pool[i] for i in indices[:r])
247 while n:
248 for i in reversed(range(r)):
249 cycles[i] -= 1
250 if cycles[i] == 0:
251 indices[i:] = indices[i+1:] + indices[i:i+1]
252 cycles[i] = n - i
253 else:
254 j = cycles[i]
255 indices[i], indices[-j] = indices[-j], indices[i]
256 yield tuple(pool[i] for i in indices[:r])
257 break
258 else:
259 return
260
261 def permutations2(iterable, r=None):
262 'Pure python version shown in the docs'
263 pool = tuple(iterable)
264 n = len(pool)
265 r = n if r is None else r
266 for indices in product(range(n), repeat=r):
267 if len(set(indices)) == r:
268 yield tuple(pool[i] for i in indices)
269
270 for n in range(7):
271 values = [5*x-12 for x in range(n)]
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000272 for r in range(n+2):
Raymond Hettingerd553d852008-03-04 04:17:08 +0000273 result = list(permutations(values, r))
Ezio Melottidde5b942010-02-03 05:37:26 +0000274 self.assertEqual(len(result), 0 if r>n else fact(n) // fact(n-r)) # right number of perms
Raymond Hettingerd553d852008-03-04 04:17:08 +0000275 self.assertEqual(len(result), len(set(result))) # no repeats
276 self.assertEqual(result, sorted(result)) # lexicographic order
277 for p in result:
278 self.assertEqual(len(p), r) # r-length permutations
279 self.assertEqual(len(set(p)), r) # no duplicate elements
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000280 self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
Raymond Hettingerd553d852008-03-04 04:17:08 +0000281 self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000282 self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
Raymond Hettingerd553d852008-03-04 04:17:08 +0000283 if r == n:
284 self.assertEqual(result, list(permutations(values, None))) # test r as None
285 self.assertEqual(result, list(permutations(values))) # test default r
286
Benjamin Petersondda91212015-02-01 21:34:07 -0500287 @test_support.bigaddrspacetest
288 def test_permutations_overflow(self):
289 with self.assertRaises(OverflowError):
290 permutations("A", 2**30)
291 with self.assertRaises(OverflowError):
292 permutations("A", 2, 2**30)
293
Zachary Ware4e0df172014-04-24 13:20:27 -0500294 @test_support.impl_detail("tuple reuse is specific to CPython")
Alex Gaynor97376482011-07-17 16:44:31 -0700295 def test_permutations_tuple_reuse(self):
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000296 self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000297 self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000298
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000299 def test_combinatorics(self):
300 # Test relationships between product(), permutations(),
301 # combinations() and combinations_with_replacement().
302
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000303 for n in range(6):
304 s = 'ABCDEFG'[:n]
305 for r in range(8):
306 prod = list(product(s, repeat=r))
307 cwr = list(combinations_with_replacement(s, r))
308 perm = list(permutations(s, r))
309 comb = list(combinations(s, r))
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000310
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000311 # Check size
Ezio Melotti2623a372010-11-21 13:34:58 +0000312 self.assertEqual(len(prod), n**r)
313 self.assertEqual(len(cwr), (fact(n+r-1) // fact(r) // fact(n-1)) if n else (not r))
314 self.assertEqual(len(perm), 0 if r>n else fact(n) // fact(n-r))
315 self.assertEqual(len(comb), 0 if r>n else fact(n) // fact(r) // fact(n-r))
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000316
317 # Check lexicographic order without repeated tuples
Ezio Melotti2623a372010-11-21 13:34:58 +0000318 self.assertEqual(prod, sorted(set(prod)))
319 self.assertEqual(cwr, sorted(set(cwr)))
320 self.assertEqual(perm, sorted(set(perm)))
321 self.assertEqual(comb, sorted(set(comb)))
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000322
323 # Check interrelationships
Ezio Melotti2623a372010-11-21 13:34:58 +0000324 self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
325 self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000326 self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted
327 self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups
328 self.assertEqual(comb, filter(set(cwr).__contains__, perm)) # comb: perm that is a cwr
329 self.assertEqual(comb, filter(set(perm).__contains__, cwr)) # comb: cwr that is a perm
330 self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000331
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000332 def test_compress(self):
Raymond Hettinger2e2909f2009-02-19 02:15:14 +0000333 self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000334 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
335 self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list(''))
336 self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF'))
337 self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC'))
338 self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC'))
339 n = 10000
340 data = chain.from_iterable(repeat(range(6), n))
341 selectors = chain.from_iterable(repeat((0, 1)))
342 self.assertEqual(list(compress(data, selectors)), [1,3,5] * n)
343 self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable
344 self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable
345 self.assertRaises(TypeError, compress, range(6)) # too few args
346 self.assertRaises(TypeError, compress, range(6), None) # too many args
347
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000348 def test_count(self):
349 self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
350 self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
Raymond Hettinger02420702003-06-29 20:36:23 +0000351 self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)])
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000352 self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
353 self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000354 self.assertRaises(TypeError, count, 2, 3, 4)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000355 self.assertRaises(TypeError, count, 'a')
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000356 self.assertEqual(list(islice(count(maxsize-5), 10)), range(maxsize-5, maxsize+5))
357 self.assertEqual(list(islice(count(-maxsize-5), 10)), range(-maxsize-5, -maxsize+5))
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000358 c = count(3)
359 self.assertEqual(repr(c), 'count(3)')
360 c.next()
361 self.assertEqual(repr(c), 'count(4)')
Jack Diederich36234e82006-09-21 17:50:26 +0000362 c = count(-9)
363 self.assertEqual(repr(c), 'count(-9)')
364 c.next()
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000365 self.assertEqual(repr(count(10.25)), 'count(10.25)')
Jack Diederich36234e82006-09-21 17:50:26 +0000366 self.assertEqual(c.next(), -8)
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000367 for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
Raymond Hettinger3a0de082007-10-12 17:53:11 +0000368 # Test repr (ignoring the L in longs)
369 r1 = repr(count(i)).replace('L', '')
370 r2 = 'count(%r)'.__mod__(i).replace('L', '')
371 self.assertEqual(r1, r2)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000372
Raymond Hettingere09f45a2009-11-30 19:44:40 +0000373 # check copy, deepcopy, pickle
374 for value in -3, 3, sys.maxint-5, sys.maxint+5:
375 c = count(value)
376 self.assertEqual(next(copy.copy(c)), value)
377 self.assertEqual(next(copy.deepcopy(c)), value)
Serhiy Storchaka655720e2014-12-15 14:02:43 +0200378 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
379 self.assertEqual(next(pickle.loads(pickle.dumps(c, proto))), value)
Raymond Hettingere09f45a2009-11-30 19:44:40 +0000380
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000381 def test_count_with_stride(self):
382 self.assertEqual(zip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingera4038032009-02-14 00:25:51 +0000383 self.assertEqual(zip('abc',count(start=2,step=3)),
384 [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingeraa681c72009-02-21 07:17:22 +0000385 self.assertEqual(zip('abc',count(step=-1)),
386 [('a', 0), ('b', -1), ('c', -2)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000387 self.assertEqual(zip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
388 self.assertEqual(zip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
389 self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
390 self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
391 self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
Raymond Hettingeraa044612009-02-12 12:04:26 +0000392 self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
393 [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
Raymond Hettingerdbe3bfb2009-02-12 12:43:01 +0000394 self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
395 [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000396 self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
397 c = count(3, 5)
398 self.assertEqual(repr(c), 'count(3, 5)')
399 c.next()
400 self.assertEqual(repr(c), 'count(8, 5)')
401 c = count(-9, 0)
402 self.assertEqual(repr(c), 'count(-9, 0)')
403 c.next()
404 self.assertEqual(repr(c), 'count(-9, 0)')
405 c = count(-9, -3)
406 self.assertEqual(repr(c), 'count(-9, -3)')
407 c.next()
408 self.assertEqual(repr(c), 'count(-12, -3)')
409 self.assertEqual(repr(c), 'count(-12, -3)')
410 self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
411 self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int
412 self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0
413 for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
414 for j in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 1, 10, sys.maxint-5, sys.maxint+5):
415 # Test repr (ignoring the L in longs)
416 r1 = repr(count(i, j)).replace('L', '')
417 if j == 1:
418 r2 = ('count(%r)' % i).replace('L', '')
419 else:
420 r2 = ('count(%r, %r)' % (i, j)).replace('L', '')
421 self.assertEqual(r1, r2)
422
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000423 def test_cycle(self):
Raymond Hettinger02420702003-06-29 20:36:23 +0000424 self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000425 self.assertEqual(list(cycle('')), [])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000426 self.assertRaises(TypeError, cycle)
427 self.assertRaises(TypeError, cycle, 5)
428 self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000429
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000430 def test_groupby(self):
431 # Check whether it accepts arguments correctly
432 self.assertEqual([], list(groupby([])))
433 self.assertEqual([], list(groupby([], key=id)))
434 self.assertRaises(TypeError, list, groupby('abc', []))
435 self.assertRaises(TypeError, groupby, None)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000436 self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000437
438 # Check normal input
439 s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
440 (2,15,22), (3,16,23), (3,17,23)]
441 dup = []
442 for k, g in groupby(s, lambda r:r[0]):
443 for elem in g:
444 self.assertEqual(k, elem[0])
445 dup.append(elem)
446 self.assertEqual(s, dup)
447
448 # Check nested case
449 dup = []
450 for k, g in groupby(s, lambda r:r[0]):
451 for ik, ig in groupby(g, lambda r:r[2]):
452 for elem in ig:
453 self.assertEqual(k, elem[0])
454 self.assertEqual(ik, elem[2])
455 dup.append(elem)
456 self.assertEqual(s, dup)
457
458 # Check case where inner iterator is not used
459 keys = [k for k, g in groupby(s, lambda r:r[0])]
460 expectedkeys = set([r[0] for r in s])
461 self.assertEqual(set(keys), expectedkeys)
462 self.assertEqual(len(keys), len(expectedkeys))
463
464 # Exercise pipes and filters style
465 s = 'abracadabra'
466 # sort s | uniq
Raymond Hettinger64958a12003-12-17 20:43:33 +0000467 r = [k for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000468 self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
469 # sort s | uniq -d
Raymond Hettinger64958a12003-12-17 20:43:33 +0000470 r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000471 self.assertEqual(r, ['a', 'b', 'r'])
472 # sort s | uniq -c
Raymond Hettinger64958a12003-12-17 20:43:33 +0000473 r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000474 self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
475 # sort s | uniq -c | sort -rn | head -3
Raymond Hettinger64958a12003-12-17 20:43:33 +0000476 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000477 self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
478
479 # iter.next failure
480 class ExpectedError(Exception):
481 pass
482 def delayed_raise(n=0):
483 for i in range(n):
484 yield 'yo'
485 raise ExpectedError
486 def gulp(iterable, keyp=None, func=list):
487 return [func(g) for k, g in groupby(iterable, keyp)]
488
489 # iter.next failure on outer object
490 self.assertRaises(ExpectedError, gulp, delayed_raise(0))
491 # iter.next failure on inner object
492 self.assertRaises(ExpectedError, gulp, delayed_raise(1))
493
494 # __cmp__ failure
495 class DummyCmp:
496 def __cmp__(self, dst):
497 raise ExpectedError
498 s = [DummyCmp(), DummyCmp(), None]
499
500 # __cmp__ failure on outer object
501 self.assertRaises(ExpectedError, gulp, s, func=id)
502 # __cmp__ failure on inner object
503 self.assertRaises(ExpectedError, gulp, s)
504
505 # keyfunc failure
506 def keyfunc(obj):
507 if keyfunc.skip > 0:
508 keyfunc.skip -= 1
509 return obj
510 else:
511 raise ExpectedError
512
513 # keyfunc failure on outer object
514 keyfunc.skip = 0
515 self.assertRaises(ExpectedError, gulp, [None], keyfunc)
516 keyfunc.skip = 1
517 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
518
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000519 def test_ifilter(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000520 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000521 self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
Raymond Hettinger9d638372008-02-25 22:42:32 +0000522 self.assertEqual(list(ifilter(bool, [0,1,0,2,0])), [1,2])
Raymond Hettinger02420702003-06-29 20:36:23 +0000523 self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000524 self.assertRaises(TypeError, ifilter)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000525 self.assertRaises(TypeError, ifilter, lambda x:x)
526 self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000527 self.assertRaises(TypeError, ifilter, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000528 self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000529
530 def test_ifilterfalse(self):
Raymond Hettinger60eca932003-02-09 06:40:58 +0000531 self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
532 self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
Raymond Hettinger9d638372008-02-25 22:42:32 +0000533 self.assertEqual(list(ifilterfalse(bool, [0,1,0,2,0])), [0,0,0])
Raymond Hettinger02420702003-06-29 20:36:23 +0000534 self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7])
Raymond Hettinger60eca932003-02-09 06:40:58 +0000535 self.assertRaises(TypeError, ifilterfalse)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000536 self.assertRaises(TypeError, ifilterfalse, lambda x:x)
537 self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000538 self.assertRaises(TypeError, ifilterfalse, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000539 self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000540
541 def test_izip(self):
542 ans = [(x,y) for x, y in izip('abc',count())]
543 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000544 self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6)))
545 self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3)))
Raymond Hettinger02420702003-06-29 20:36:23 +0000546 self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3)))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000547 self.assertEqual(list(izip('abcdef')), zip('abcdef'))
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000548 self.assertEqual(list(izip()), zip())
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000549 self.assertRaises(TypeError, izip, 3)
550 self.assertRaises(TypeError, izip, range(3), 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000551 self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
552 zip('abc', 'def'))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000553 self.assertEqual([pair for pair in izip('abc', 'def')],
554 zip('abc', 'def'))
Alex Gaynor97376482011-07-17 16:44:31 -0700555
556 @test_support.impl_detail("tuple reuse is specific to CPython")
Zachary Ware4e0df172014-04-24 13:20:27 -0500557 def test_izip_tuple_reuse(self):
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000558 ids = map(id, izip('abc', 'def'))
559 self.assertEqual(min(ids), max(ids))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000560 ids = map(id, list(izip('abc', 'def')))
561 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000562
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000563 def test_iziplongest(self):
564 for args in [
565 ['abc', range(6)],
566 [range(6), 'abc'],
567 [range(1000), range(2000,2100), range(3000,3050)],
568 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
569 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
570 ]:
Ezio Melottidde5b942010-02-03 05:37:26 +0000571 # target = map(None, *args) <- this raises a py3k warning
572 # this is the replacement:
573 target = [tuple([arg[i] if i < len(arg) else None for arg in args])
574 for i in range(max(map(len, args)))]
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000575 self.assertEqual(list(izip_longest(*args)), target)
576 self.assertEqual(list(izip_longest(*args, **{})), target)
577 target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
578 self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target)
Tim Petersea5962f2007-03-12 18:07:52 +0000579
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000580 self.assertEqual(take(3,izip_longest('abcdef', count())), zip('abcdef', range(3))) # take 3 from infinite input
581
582 self.assertEqual(list(izip_longest()), zip())
583 self.assertEqual(list(izip_longest([])), zip([]))
584 self.assertEqual(list(izip_longest('abcdef')), zip('abcdef'))
Tim Petersea5962f2007-03-12 18:07:52 +0000585
Ezio Melottidde5b942010-02-03 05:37:26 +0000586 self.assertEqual(list(izip_longest('abc', 'defg', **{})),
587 zip(list('abc') + [None], 'defg')) # empty keyword dict
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000588 self.assertRaises(TypeError, izip_longest, 3)
589 self.assertRaises(TypeError, izip_longest, range(3), 3)
590
591 for stmt in [
592 "izip_longest('abc', fv=1)",
Tim Petersea5962f2007-03-12 18:07:52 +0000593 "izip_longest('abc', fillvalue=1, bogus_keyword=None)",
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000594 ]:
595 try:
596 eval(stmt, globals(), locals())
597 except TypeError:
598 pass
599 else:
600 self.fail('Did not raise Type in: ' + stmt)
Tim Petersea5962f2007-03-12 18:07:52 +0000601
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000602 self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')],
603 zip('abc', 'def'))
604 self.assertEqual([pair for pair in izip_longest('abc', 'def')],
605 zip('abc', 'def'))
Alex Gaynor97376482011-07-17 16:44:31 -0700606
607 @test_support.impl_detail("tuple reuse is specific to CPython")
608 def test_izip_longest_tuple_reuse(self):
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000609 ids = map(id, izip_longest('abc', 'def'))
610 self.assertEqual(min(ids), max(ids))
611 ids = map(id, list(izip_longest('abc', 'def')))
612 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
613
Raymond Hettingerfa7dadd2009-11-01 20:45:16 +0000614 def test_bug_7244(self):
615
616 class Repeater(object):
617 # this class is similar to itertools.repeat
618 def __init__(self, o, t, e):
619 self.o = o
620 self.t = int(t)
621 self.e = e
622 def __iter__(self): # its iterator is itself
623 return self
624 def next(self):
625 if self.t > 0:
626 self.t -= 1
627 return self.o
628 else:
629 raise self.e
630
631 # Formerly this code in would fail in debug mode
632 # with Undetected Error and Stop Iteration
633 r1 = Repeater(1, 3, StopIteration)
634 r2 = Repeater(2, 4, StopIteration)
635 def run(r1, r2):
636 result = []
637 for i, j in izip_longest(r1, r2, fillvalue=0):
638 with test_support.captured_output('stdout'):
639 print (i, j)
640 result.append((i, j))
641 return result
642 self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])
643
644 # Formerly, the RuntimeError would be lost
645 # and StopIteration would stop as expected
646 r1 = Repeater(1, 3, RuntimeError)
647 r2 = Repeater(2, 4, StopIteration)
648 it = izip_longest(r1, r2, fillvalue=0)
649 self.assertEqual(next(it), (1, 2))
650 self.assertEqual(next(it), (1, 2))
651 self.assertEqual(next(it), (1, 2))
652 self.assertRaises(RuntimeError, next, it)
653
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000654 def test_product(self):
655 for args, result in [
Raymond Hettingerd553d852008-03-04 04:17:08 +0000656 ([], [()]), # zero iterables
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000657 (['ab'], [('a',), ('b',)]), # one iterable
658 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
659 ([range(0), range(2), range(3)], []), # first iterable with zero length
660 ([range(2), range(0), range(3)], []), # middle iterable with zero length
661 ([range(2), range(3), range(0)], []), # last iterable with zero length
662 ]:
663 self.assertEqual(list(product(*args)), result)
Raymond Hettinger08ff6822008-02-29 02:21:48 +0000664 for r in range(4):
665 self.assertEqual(list(product(*(args*r))),
666 list(product(*args, **dict(repeat=r))))
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000667 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
668 self.assertRaises(TypeError, product, range(6), None)
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000669
Raymond Hettinger38fb9be2008-03-07 01:33:20 +0000670 def product1(*args, **kwds):
671 pools = map(tuple, args) * kwds.get('repeat', 1)
672 n = len(pools)
673 if n == 0:
674 yield ()
675 return
676 if any(len(pool) == 0 for pool in pools):
677 return
678 indices = [0] * n
679 yield tuple(pool[i] for pool, i in zip(pools, indices))
680 while 1:
681 for i in reversed(range(n)): # right to left
682 if indices[i] == len(pools[i]) - 1:
683 continue
684 indices[i] += 1
685 for j in range(i+1, n):
686 indices[j] = 0
687 yield tuple(pool[i] for pool, i in zip(pools, indices))
688 break
689 else:
690 return
691
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000692 def product2(*args, **kwds):
693 'Pure python version used in docs'
694 pools = map(tuple, args) * kwds.get('repeat', 1)
695 result = [[]]
696 for pool in pools:
697 result = [x+[y] for x in result for y in pool]
698 for prod in result:
699 yield tuple(prod)
700
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000701 argtypes = ['', 'abc', '', xrange(0), xrange(4), dict(a=1, b=2, c=3),
702 set('abcdefg'), range(11), tuple(range(13))]
703 for i in range(100):
704 args = [random.choice(argtypes) for j in range(random.randrange(5))]
Raymond Hettingerd553d852008-03-04 04:17:08 +0000705 expected_len = prod(map(len, args))
706 self.assertEqual(len(list(product(*args))), expected_len)
Raymond Hettinger38fb9be2008-03-07 01:33:20 +0000707 self.assertEqual(list(product(*args)), list(product1(*args)))
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000708 self.assertEqual(list(product(*args)), list(product2(*args)))
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000709 args = map(iter, args)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000710 self.assertEqual(len(list(product(*args))), expected_len)
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000711
Benjamin Petersondda91212015-02-01 21:34:07 -0500712 @test_support.bigaddrspacetest
713 def test_product_overflow(self):
714 with self.assertRaises(OverflowError):
715 product(["a"]*(2**16), repeat=2**16)
716
Alex Gaynor97376482011-07-17 16:44:31 -0700717 @test_support.impl_detail("tuple reuse is specific to CPython")
718 def test_product_tuple_reuse(self):
Raymond Hettinger73d79632008-02-23 02:20:41 +0000719 self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
720 self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000721
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000722 def test_repeat(self):
Raymond Hettinger182edae2009-02-19 02:38:25 +0000723 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
Raymond Hettinger58ad2452014-06-24 21:53:45 -0700724 self.assertEqual(list(repeat(object='a', times=0)), [])
725 self.assertEqual(list(repeat(object='a', times=-1)), [])
726 self.assertEqual(list(repeat(object='a', times=-2)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000727 self.assertEqual(zip(xrange(3),repeat('a')),
728 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000729 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger02420702003-06-29 20:36:23 +0000730 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000731 self.assertEqual(list(repeat('a', 0)), [])
732 self.assertEqual(list(repeat('a', -3)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000733 self.assertRaises(TypeError, repeat)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000734 self.assertRaises(TypeError, repeat, None, 3, 4)
735 self.assertRaises(TypeError, repeat, None, 'a')
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000736 r = repeat(1+0j)
737 self.assertEqual(repr(r), 'repeat((1+0j))')
738 r = repeat(1+0j, 5)
739 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
740 list(r)
741 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000742
Raymond Hettinger58ad2452014-06-24 21:53:45 -0700743 def test_repeat_with_negative_times(self):
744 self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
745 self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
746 self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
747 self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
748
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000749 def test_imap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000750 self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
751 [0**1, 1**2, 2**3])
752 self.assertEqual(list(imap(None, 'abc', range(5))),
753 [('a',0),('b',1),('c',2)])
Raymond Hettinger02420702003-06-29 20:36:23 +0000754 self.assertEqual(list(imap(None, 'abc', count())),
755 [('a',0),('b',1),('c',2)])
756 self.assertEqual(take(2,imap(None, 'abc', count())),
757 [('a',0),('b',1)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000758 self.assertEqual(list(imap(operator.pow, [])), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000759 self.assertRaises(TypeError, imap)
760 self.assertRaises(TypeError, imap, operator.neg)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000761 self.assertRaises(TypeError, imap(10, range(5)).next)
762 self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
763 self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000764
765 def test_starmap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000766 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
767 [0**1, 1**2, 2**3])
Raymond Hettinger02420702003-06-29 20:36:23 +0000768 self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))),
769 [0**1, 1**2, 2**3])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000770 self.assertEqual(list(starmap(operator.pow, [])), [])
Raymond Hettinger47317092008-01-17 03:02:14 +0000771 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
772 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000773 self.assertRaises(TypeError, starmap)
774 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
775 self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
776 self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
777 self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000778
779 def test_islice(self):
780 for args in [ # islice(args) should agree with range(args)
781 (10, 20, 3),
782 (10, 3, 20),
783 (10, 20),
784 (10, 3),
785 (20,)
786 ]:
787 self.assertEqual(list(islice(xrange(100), *args)), range(*args))
788
789 for args, tgtargs in [ # Stop when seqn is exhausted
790 ((10, 110, 3), ((10, 100, 3))),
791 ((10, 110), ((10, 100))),
792 ((110,), (100,))
793 ]:
794 self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
795
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000796 # Test stop=None
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000797 self.assertEqual(list(islice(xrange(10), None)), range(10))
Raymond Hettingerb2594052004-12-05 09:25:51 +0000798 self.assertEqual(list(islice(xrange(10), None, None)), range(10))
799 self.assertEqual(list(islice(xrange(10), None, None, None)), range(10))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000800 self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
801 self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
802
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +0000803 # Test number of items consumed SF #1171417
804 it = iter(range(10))
805 self.assertEqual(list(islice(it, 3)), range(3))
806 self.assertEqual(list(it), range(3, 10))
807
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000808 # Test invalid arguments
Raymond Hettinger341deb72003-05-02 19:44:20 +0000809 self.assertRaises(TypeError, islice, xrange(10))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000810 self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
811 self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
812 self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
813 self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
814 self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000815 self.assertRaises(ValueError, islice, xrange(10), 'a')
816 self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
817 self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
818 self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
819 self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000820 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000821
Raymond Hettinger061bf7a2010-11-30 03:15:35 +0000822 # Issue #10323: Less islice in a predictable state
823 c = count()
824 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
825 self.assertEqual(next(c), 3)
826
Antoine Pitrou3ec903f2014-04-29 12:13:46 +0200827 # Issue #21321: check source iterator is not referenced
828 # from islice() after the latter has been exhausted
829 it = (x for x in (1, 2))
830 wr = weakref.ref(it)
831 it = islice(it, 1)
832 self.assertIsNotNone(wr())
833 list(it) # exhaust the iterator
Benjamin Petersonec9d5472014-08-24 18:07:28 -0500834 test_support.gc_collect()
Antoine Pitrou3ec903f2014-04-29 12:13:46 +0200835 self.assertIsNone(wr())
836
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000837 def test_takewhile(self):
838 data = [1, 3, 5, 20, 2, 4, 6, 8]
839 underten = lambda x: x<10
840 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000841 self.assertEqual(list(takewhile(underten, [])), [])
842 self.assertRaises(TypeError, takewhile)
843 self.assertRaises(TypeError, takewhile, operator.pow)
844 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
845 self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
846 self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000847 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
848 self.assertEqual(list(t), [1, 1, 1])
849 self.assertRaises(StopIteration, t.next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000850
851 def test_dropwhile(self):
852 data = [1, 3, 5, 20, 2, 4, 6, 8]
853 underten = lambda x: x<10
854 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000855 self.assertEqual(list(dropwhile(underten, [])), [])
856 self.assertRaises(TypeError, dropwhile)
857 self.assertRaises(TypeError, dropwhile, operator.pow)
858 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
859 self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
860 self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000861
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000862 def test_tee(self):
Raymond Hettingerad983e72003-11-12 14:32:26 +0000863 n = 200
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000864 def irange(n):
865 for i in xrange(n):
866 yield i
867
868 a, b = tee([]) # test empty iterator
869 self.assertEqual(list(a), [])
870 self.assertEqual(list(b), [])
871
872 a, b = tee(irange(n)) # test 100% interleaved
873 self.assertEqual(zip(a,b), zip(range(n),range(n)))
874
875 a, b = tee(irange(n)) # test 0% interleaved
876 self.assertEqual(list(a), range(n))
877 self.assertEqual(list(b), range(n))
878
879 a, b = tee(irange(n)) # test dealloc of leading iterator
Raymond Hettingerad983e72003-11-12 14:32:26 +0000880 for i in xrange(100):
881 self.assertEqual(a.next(), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000882 del a
883 self.assertEqual(list(b), range(n))
884
885 a, b = tee(irange(n)) # test dealloc of trailing iterator
Raymond Hettingerad983e72003-11-12 14:32:26 +0000886 for i in xrange(100):
887 self.assertEqual(a.next(), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000888 del b
Raymond Hettingerad983e72003-11-12 14:32:26 +0000889 self.assertEqual(list(a), range(100, n))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000890
891 for j in xrange(5): # test randomly interleaved
892 order = [0]*n + [1]*n
893 random.shuffle(order)
894 lists = ([], [])
895 its = tee(irange(n))
896 for i in order:
897 value = its[i].next()
898 lists[i].append(value)
899 self.assertEqual(lists[0], range(n))
900 self.assertEqual(lists[1], range(n))
901
Raymond Hettingerad983e72003-11-12 14:32:26 +0000902 # test argument format checking
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000903 self.assertRaises(TypeError, tee)
904 self.assertRaises(TypeError, tee, 3)
905 self.assertRaises(TypeError, tee, [1,2], 'x')
Raymond Hettingerad983e72003-11-12 14:32:26 +0000906 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000907
Raymond Hettingerad983e72003-11-12 14:32:26 +0000908 # tee object should be instantiable
909 a, b = tee('abc')
910 c = type(a)('def')
911 self.assertEqual(list(c), list('def'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +0000912
Raymond Hettingerad983e72003-11-12 14:32:26 +0000913 # test long-lagged and multi-way split
914 a, b, c = tee(xrange(2000), 3)
915 for i in xrange(100):
916 self.assertEqual(a.next(), i)
917 self.assertEqual(list(b), range(2000))
918 self.assertEqual([c.next(), c.next()], range(2))
919 self.assertEqual(list(a), range(100,2000))
920 self.assertEqual(list(c), range(2,2000))
921
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000922 # test values of n
923 self.assertRaises(TypeError, tee, 'abc', 'invalid')
Neal Norwitz69e88972006-09-02 02:58:13 +0000924 self.assertRaises(ValueError, tee, [], -1)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000925 for n in xrange(5):
926 result = tee('abc', n)
927 self.assertEqual(type(result), tuple)
928 self.assertEqual(len(result), n)
929 self.assertEqual(map(list, result), [list('abc')]*n)
930
Raymond Hettingerad983e72003-11-12 14:32:26 +0000931 # tee pass-through to copyable iterator
932 a, b = tee('abc')
933 c, d = tee(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000934 self.assertTrue(a is c)
Raymond Hettingerad983e72003-11-12 14:32:26 +0000935
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000936 # test tee_new
937 t1, t2 = tee('abc')
938 tnew = type(t1)
939 self.assertRaises(TypeError, tnew)
940 self.assertRaises(TypeError, tnew, 10)
941 t3 = tnew(t1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000942 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +0000943
Raymond Hettingera9f60922004-10-17 16:40:14 +0000944 # test that tee objects are weak referencable
945 a, b = tee(xrange(10))
Antoine Pitrou3ec903f2014-04-29 12:13:46 +0200946 p = weakref.proxy(a)
Raymond Hettingera9f60922004-10-17 16:40:14 +0000947 self.assertEqual(getattr(p, '__class__'), type(b))
948 del a
949 self.assertRaises(ReferenceError, getattr, p, '__class__')
950
Serhiy Storchakab09ec9b2013-01-25 13:31:05 +0200951 # Issue 13454: Crash when deleting backward iterator from tee()
952 def test_tee_del_backward(self):
Serhiy Storchaka6fef14d2013-01-26 11:51:42 +0200953 forward, backward = tee(repeat(None, 20000000))
954 any(forward) # exhaust the iterator
Serhiy Storchakab09ec9b2013-01-25 13:31:05 +0200955 del backward
956
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000957 def test_StopIteration(self):
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000958 self.assertRaises(StopIteration, izip().next)
959
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000960 for f in (chain, cycle, izip, groupby):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000961 self.assertRaises(StopIteration, f([]).next)
962 self.assertRaises(StopIteration, f(StopNow()).next)
963
964 self.assertRaises(StopIteration, islice([], None).next)
965 self.assertRaises(StopIteration, islice(StopNow(), None).next)
966
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000967 p, q = tee([])
968 self.assertRaises(StopIteration, p.next)
969 self.assertRaises(StopIteration, q.next)
970 p, q = tee(StopNow())
971 self.assertRaises(StopIteration, p.next)
972 self.assertRaises(StopIteration, q.next)
973
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000974 self.assertRaises(StopIteration, repeat(None, 0).next)
975
976 for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
977 self.assertRaises(StopIteration, f(lambda x:x, []).next)
978 self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
979
Raymond Hettingerad47fa12008-03-06 20:52:01 +0000980class TestExamples(unittest.TestCase):
981
982 def test_chain(self):
983 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
984
985 def test_chain_from_iterable(self):
986 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
987
988 def test_combinations(self):
989 self.assertEqual(list(combinations('ABCD', 2)),
990 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
991 self.assertEqual(list(combinations(range(4), 3)),
992 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
993
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000994 def test_combinations_with_replacement(self):
995 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
996 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
997
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000998 def test_compress(self):
999 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
1000
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001001 def test_count(self):
1002 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
1003
1004 def test_cycle(self):
1005 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
1006
1007 def test_dropwhile(self):
1008 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
1009
1010 def test_groupby(self):
1011 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
1012 list('ABCDAB'))
1013 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
1014 [list('AAAA'), list('BBB'), list('CC'), list('D')])
1015
1016 def test_ifilter(self):
1017 self.assertEqual(list(ifilter(lambda x: x%2, range(10))), [1,3,5,7,9])
1018
1019 def test_ifilterfalse(self):
1020 self.assertEqual(list(ifilterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
1021
1022 def test_imap(self):
1023 self.assertEqual(list(imap(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
1024
1025 def test_islice(self):
1026 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
1027 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
1028 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
1029 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1030
1031 def test_izip(self):
1032 self.assertEqual(list(izip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
1033
1034 def test_izip_longest(self):
1035 self.assertEqual(list(izip_longest('ABCD', 'xy', fillvalue='-')),
1036 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
1037
1038 def test_permutations(self):
1039 self.assertEqual(list(permutations('ABCD', 2)),
1040 map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split()))
1041 self.assertEqual(list(permutations(range(3))),
1042 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
1043
1044 def test_product(self):
1045 self.assertEqual(list(product('ABCD', 'xy')),
1046 map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split()))
1047 self.assertEqual(list(product(range(2), repeat=3)),
1048 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1049 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1050
1051 def test_repeat(self):
1052 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1053
1054 def test_stapmap(self):
1055 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1056 [32, 9, 1000])
1057
1058 def test_takewhile(self):
1059 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1060
1061
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001062class TestGC(unittest.TestCase):
1063
1064 def makecycle(self, iterator, container):
1065 container.append(iterator)
1066 iterator.next()
1067 del container, iterator
1068
1069 def test_chain(self):
1070 a = []
1071 self.makecycle(chain(a), a)
1072
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001073 def test_chain_from_iterable(self):
1074 a = []
1075 self.makecycle(chain.from_iterable([a]), a)
1076
1077 def test_combinations(self):
1078 a = []
1079 self.makecycle(combinations([1,2,a,3], 3), a)
1080
Raymond Hettingerd081abc2009-01-27 02:58:49 +00001081 def test_combinations_with_replacement(self):
1082 a = []
1083 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1084
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001085 def test_compress(self):
1086 a = []
1087 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1088
Raymond Hettingerb21d8102009-02-16 20:39:12 +00001089 def test_count(self):
1090 a = []
1091 Int = type('Int', (int,), dict(x=a))
1092 self.makecycle(count(Int(0), Int(1)), a)
1093
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001094 def test_cycle(self):
1095 a = []
1096 self.makecycle(cycle([a]*2), a)
1097
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001098 def test_dropwhile(self):
1099 a = []
1100 self.makecycle(dropwhile(bool, [0, a, a]), a)
1101
1102 def test_groupby(self):
1103 a = []
1104 self.makecycle(groupby([a]*2, lambda x:x), a)
1105
Raymond Hettingera1ca94a2008-03-06 22:51:36 +00001106 def test_issue2246(self):
1107 # Issue 2246 -- the _grouper iterator was not included in GC
1108 n = 10
1109 keyfunc = lambda x: x
1110 for i, j in groupby(xrange(n), key=keyfunc):
1111 keyfunc.__dict__.setdefault('x',[]).append(j)
1112
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001113 def test_ifilter(self):
1114 a = []
1115 self.makecycle(ifilter(lambda x:True, [a]*2), a)
1116
1117 def test_ifilterfalse(self):
1118 a = []
1119 self.makecycle(ifilterfalse(lambda x:False, a), a)
1120
1121 def test_izip(self):
1122 a = []
1123 self.makecycle(izip([a]*2, [a]*3), a)
1124
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001125 def test_izip_longest(self):
1126 a = []
1127 self.makecycle(izip_longest([a]*2, [a]*3), a)
1128 b = [a, None]
1129 self.makecycle(izip_longest([a]*2, [a]*3, fillvalue=b), a)
1130
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001131 def test_imap(self):
1132 a = []
1133 self.makecycle(imap(lambda x:x, [a]*2), a)
1134
1135 def test_islice(self):
1136 a = []
1137 self.makecycle(islice([a]*2, None), a)
1138
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001139 def test_permutations(self):
1140 a = []
1141 self.makecycle(permutations([1,2,a,3], 3), a)
1142
1143 def test_product(self):
1144 a = []
1145 self.makecycle(product([1,2,a,3], repeat=3), a)
1146
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001147 def test_repeat(self):
1148 a = []
1149 self.makecycle(repeat(a), a)
1150
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001151 def test_starmap(self):
1152 a = []
1153 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1154
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001155 def test_takewhile(self):
1156 a = []
1157 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1158
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001159def R(seqn):
1160 'Regular generator'
1161 for i in seqn:
1162 yield i
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001163
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001164class G:
1165 'Sequence using __getitem__'
1166 def __init__(self, seqn):
1167 self.seqn = seqn
1168 def __getitem__(self, i):
1169 return self.seqn[i]
1170
1171class I:
1172 'Sequence using iterator protocol'
1173 def __init__(self, seqn):
1174 self.seqn = seqn
1175 self.i = 0
1176 def __iter__(self):
1177 return self
1178 def next(self):
1179 if self.i >= len(self.seqn): raise StopIteration
1180 v = self.seqn[self.i]
1181 self.i += 1
1182 return v
1183
1184class Ig:
1185 'Sequence using iterator protocol defined with a generator'
1186 def __init__(self, seqn):
1187 self.seqn = seqn
1188 self.i = 0
1189 def __iter__(self):
1190 for val in self.seqn:
1191 yield val
1192
1193class X:
1194 'Missing __getitem__ and __iter__'
1195 def __init__(self, seqn):
1196 self.seqn = seqn
1197 self.i = 0
1198 def next(self):
1199 if self.i >= len(self.seqn): raise StopIteration
1200 v = self.seqn[self.i]
1201 self.i += 1
1202 return v
1203
1204class N:
1205 'Iterator missing next()'
1206 def __init__(self, seqn):
1207 self.seqn = seqn
1208 self.i = 0
1209 def __iter__(self):
1210 return self
1211
1212class E:
1213 'Test propagation of exceptions'
1214 def __init__(self, seqn):
1215 self.seqn = seqn
1216 self.i = 0
1217 def __iter__(self):
1218 return self
1219 def next(self):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +00001220 3 // 0
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001221
1222class S:
1223 'Test immediate stop'
1224 def __init__(self, seqn):
1225 pass
1226 def __iter__(self):
1227 return self
1228 def next(self):
1229 raise StopIteration
1230
1231def L(seqn):
1232 'Test multiple tiers of iterators'
1233 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
1234
1235
1236class TestVariousIteratorArgs(unittest.TestCase):
1237
1238 def test_chain(self):
1239 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1240 for g in (G, I, Ig, S, L, R):
1241 self.assertEqual(list(chain(g(s))), list(g(s)))
1242 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
Raymond Hettinger05bf6332008-02-28 22:30:42 +00001243 self.assertRaises(TypeError, list, chain(X(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001244 self.assertRaises(TypeError, list, chain(N(s)))
1245 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
1246
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001247 def test_compress(self):
1248 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1249 n = len(s)
1250 for g in (G, I, Ig, S, L, R):
1251 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
1252 self.assertRaises(TypeError, compress, X(s), repeat(1))
1253 self.assertRaises(TypeError, list, compress(N(s), repeat(1)))
1254 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
1255
Raymond Hettinger50986cc2008-02-22 03:16:42 +00001256 def test_product(self):
1257 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1258 self.assertRaises(TypeError, product, X(s))
1259 self.assertRaises(TypeError, product, N(s))
1260 self.assertRaises(ZeroDivisionError, product, E(s))
1261
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001262 def test_cycle(self):
1263 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1264 for g in (G, I, Ig, S, L, R):
1265 tgtlen = len(s) * 3
1266 expected = list(g(s))*3
1267 actual = list(islice(cycle(g(s)), tgtlen))
1268 self.assertEqual(actual, expected)
1269 self.assertRaises(TypeError, cycle, X(s))
1270 self.assertRaises(TypeError, list, cycle(N(s)))
1271 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
1272
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001273 def test_groupby(self):
1274 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1275 for g in (G, I, Ig, S, L, R):
1276 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
1277 self.assertRaises(TypeError, groupby, X(s))
1278 self.assertRaises(TypeError, list, groupby(N(s)))
1279 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
1280
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001281 def test_ifilter(self):
1282 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1283 for g in (G, I, Ig, S, L, R):
1284 self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
1285 self.assertRaises(TypeError, ifilter, isEven, X(s))
1286 self.assertRaises(TypeError, list, ifilter(isEven, N(s)))
1287 self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
1288
1289 def test_ifilterfalse(self):
1290 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1291 for g in (G, I, Ig, S, L, R):
1292 self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
1293 self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
1294 self.assertRaises(TypeError, list, ifilterfalse(isEven, N(s)))
1295 self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
1296
1297 def test_izip(self):
1298 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1299 for g in (G, I, Ig, S, L, R):
1300 self.assertEqual(list(izip(g(s))), zip(g(s)))
1301 self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s)))
1302 self.assertRaises(TypeError, izip, X(s))
1303 self.assertRaises(TypeError, list, izip(N(s)))
1304 self.assertRaises(ZeroDivisionError, list, izip(E(s)))
1305
Raymond Hettingerd36862c2007-02-21 05:20:38 +00001306 def test_iziplongest(self):
1307 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1308 for g in (G, I, Ig, S, L, R):
1309 self.assertEqual(list(izip_longest(g(s))), zip(g(s)))
1310 self.assertEqual(list(izip_longest(g(s), g(s))), zip(g(s), g(s)))
1311 self.assertRaises(TypeError, izip_longest, X(s))
1312 self.assertRaises(TypeError, list, izip_longest(N(s)))
1313 self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
1314
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001315 def test_imap(self):
1316 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1317 for g in (G, I, Ig, S, L, R):
1318 self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
1319 self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
1320 self.assertRaises(TypeError, imap, onearg, X(s))
1321 self.assertRaises(TypeError, list, imap(onearg, N(s)))
1322 self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
1323
1324 def test_islice(self):
1325 for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1326 for g in (G, I, Ig, S, L, R):
1327 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
1328 self.assertRaises(TypeError, islice, X(s), 10)
1329 self.assertRaises(TypeError, list, islice(N(s), 10))
1330 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
1331
1332 def test_starmap(self):
1333 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1334 for g in (G, I, Ig, S, L, R):
1335 ss = zip(s, s)
1336 self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
1337 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
1338 self.assertRaises(TypeError, list, starmap(operator.pow, N(ss)))
1339 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
1340
1341 def test_takewhile(self):
1342 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1343 for g in (G, I, Ig, S, L, R):
1344 tgt = []
1345 for elem in g(s):
1346 if not isEven(elem): break
1347 tgt.append(elem)
1348 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
1349 self.assertRaises(TypeError, takewhile, isEven, X(s))
1350 self.assertRaises(TypeError, list, takewhile(isEven, N(s)))
1351 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
1352
1353 def test_dropwhile(self):
1354 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1355 for g in (G, I, Ig, S, L, R):
1356 tgt = []
1357 for elem in g(s):
1358 if not tgt and isOdd(elem): continue
1359 tgt.append(elem)
1360 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
1361 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
1362 self.assertRaises(TypeError, list, dropwhile(isOdd, N(s)))
1363 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
1364
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001365 def test_tee(self):
1366 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1367 for g in (G, I, Ig, S, L, R):
1368 it1, it2 = tee(g(s))
1369 self.assertEqual(list(it1), list(g(s)))
1370 self.assertEqual(list(it2), list(g(s)))
1371 self.assertRaises(TypeError, tee, X(s))
1372 self.assertRaises(TypeError, list, tee(N(s))[0])
1373 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
1374
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001375class LengthTransparency(unittest.TestCase):
1376
1377 def test_repeat(self):
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001378 from test.test_iterlen import len
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001379 self.assertEqual(len(repeat(None, 50)), 50)
1380 self.assertRaises(TypeError, len, repeat(None))
1381
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001382class RegressionTests(unittest.TestCase):
1383
1384 def test_sf_793826(self):
1385 # Fix Armin Rigo's successful efforts to wreak havoc
1386
1387 def mutatingtuple(tuple1, f, tuple2):
1388 # this builds a tuple t which is a copy of tuple1,
1389 # then calls f(t), then mutates t to be equal to tuple2
1390 # (needs len(tuple1) == len(tuple2)).
1391 def g(value, first=[1]):
1392 if first:
1393 del first[:]
1394 f(z.next())
1395 return value
1396 items = list(tuple2)
1397 items[1:1] = list(tuple1)
1398 gen = imap(g, items)
1399 z = izip(*[gen]*len(tuple1))
1400 z.next()
1401
1402 def f(t):
1403 global T
1404 T = t
1405 first[:] = list(T)
1406
1407 first = []
1408 mutatingtuple((1,2,3), f, (4,5,6))
1409 second = list(T)
1410 self.assertEqual(first, second)
1411
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001412
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001413 def test_sf_950057(self):
1414 # Make sure that chain() and cycle() catch exceptions immediately
1415 # rather than when shifting between input sources
1416
1417 def gen1():
1418 hist.append(0)
1419 yield 1
1420 hist.append(1)
Tim Petersbeb7c0c2004-07-18 17:34:03 +00001421 raise AssertionError
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001422 hist.append(2)
1423
1424 def gen2(x):
1425 hist.append(3)
1426 yield 2
1427 hist.append(4)
1428 if x:
1429 raise StopIteration
1430
1431 hist = []
1432 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
1433 self.assertEqual(hist, [0,1])
1434
1435 hist = []
1436 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
1437 self.assertEqual(hist, [0,1])
1438
1439 hist = []
1440 self.assertRaises(AssertionError, list, cycle(gen1()))
1441 self.assertEqual(hist, [0,1])
1442
Georg Brandlb84c1372007-01-21 10:28:43 +00001443class SubclassWithKwargsTest(unittest.TestCase):
1444 def test_keywords_in_subclass(self):
1445 # count is not subclassable...
1446 for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap,
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001447 starmap, islice, takewhile, dropwhile, cycle, compress):
Georg Brandlb84c1372007-01-21 10:28:43 +00001448 class Subclass(cls):
1449 def __init__(self, newarg=None, *args):
1450 cls.__init__(self, *args)
1451 try:
1452 Subclass(newarg=1)
1453 except TypeError, err:
1454 # we expect type errors because of wrong argument count
Ezio Melottiaa980582010-01-23 23:04:36 +00001455 self.assertNotIn("does not take keyword arguments", err.args[0])
Georg Brandlb84c1372007-01-21 10:28:43 +00001456
1457
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001458libreftest = """ Doctest for examples in the library reference: libitertools.tex
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001459
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001460
1461>>> amounts = [120.15, 764.05, 823.14]
1462>>> for checknum, amount in izip(count(1200), amounts):
1463... print 'Check %d is for $%.2f' % (checknum, amount)
1464...
1465Check 1200 is for $120.15
1466Check 1201 is for $764.05
1467Check 1202 is for $823.14
1468
1469>>> import operator
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001470>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
1471... print cube
1472...
14731
14748
147527
1476
1477>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
Raymond Hettinger3567a872003-06-28 05:44:36 +00001478>>> for name in islice(reportlines, 3, None, 2):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001479... print name.title()
1480...
1481Alex
1482Laura
1483Martin
1484Walter
1485Samuele
1486
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001487>>> from operator import itemgetter
1488>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Armin Rigoa3f09272006-05-28 19:13:17 +00001489>>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001490>>> for k, g in groupby(di, itemgetter(1)):
1491... print k, map(itemgetter(0), g)
1492...
14931 ['a', 'c', 'e']
14942 ['b', 'd', 'f']
14953 ['g']
1496
Raymond Hettinger734fb572004-01-20 20:04:40 +00001497# Find runs of consecutive numbers using groupby. The key to the solution
1498# is differencing with a range so that consecutive numbers all appear in
1499# same group.
1500>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
Ezio Melottidde5b942010-02-03 05:37:26 +00001501>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Raymond Hettinger734fb572004-01-20 20:04:40 +00001502... print map(operator.itemgetter(1), g)
1503...
1504[1]
1505[4, 5, 6]
1506[10]
1507[15, 16, 17, 18]
1508[22]
1509[25, 26, 27, 28]
1510
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001511>>> def take(n, iterable):
1512... "Return first n items of the iterable as a list"
1513... return list(islice(iterable, n))
Raymond Hettingera098b332003-09-08 23:58:40 +00001514
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001515>>> def enumerate(iterable, start=0):
1516... return izip(count(start), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001517
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001518>>> def tabulate(function, start=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001519... "Return function(0), function(1), ..."
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001520... return imap(function, count(start))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001521
Raymond Hettingerf9bce832009-02-19 05:34:35 +00001522>>> def nth(iterable, n, default=None):
1523... "Returns the nth item or a default value"
1524... return next(islice(iterable, n, None), default)
Raymond Hettinger60eca932003-02-09 06:40:58 +00001525
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001526>>> def quantify(iterable, pred=bool):
1527... "Count how many times the predicate is true"
1528... return sum(imap(pred, iterable))
Raymond Hettinger60eca932003-02-09 06:40:58 +00001529
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001530>>> def padnone(iterable):
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001531... "Returns the sequence elements and then returns None indefinitely"
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001532... return chain(iterable, repeat(None))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001533
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001534>>> def ncycles(iterable, n):
Ezio Melottic2077b02011-03-16 12:34:31 +02001535... "Returns the sequence elements n times"
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001536... return chain(*repeat(iterable, n))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001537
1538>>> def dotproduct(vec1, vec2):
1539... return sum(imap(operator.mul, vec1, vec2))
1540
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001541>>> def flatten(listOfLists):
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001542... return list(chain.from_iterable(listOfLists))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001543
1544>>> def repeatfunc(func, times=None, *args):
1545... "Repeat calls to func with specified arguments."
1546... " Example: repeatfunc(random.random)"
1547... if times is None:
1548... return starmap(func, repeat(args))
1549... else:
1550... return starmap(func, repeat(args, times))
1551
Raymond Hettingerd591f662003-10-26 15:34:50 +00001552>>> def pairwise(iterable):
1553... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1554... a, b = tee(iterable)
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001555... for elem in b:
1556... break
Raymond Hettingerad983e72003-11-12 14:32:26 +00001557... return izip(a, b)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001558
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001559>>> def grouper(n, iterable, fillvalue=None):
Raymond Hettingerefdf7062008-07-30 07:27:30 +00001560... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001561... args = [iter(iterable)] * n
Raymond Hettingerf080e6d2008-07-31 01:19:50 +00001562... return izip_longest(fillvalue=fillvalue, *args)
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001563
1564>>> def roundrobin(*iterables):
Raymond Hettingerefdf7062008-07-30 07:27:30 +00001565... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001566... # Recipe credited to George Sakkis
1567... pending = len(iterables)
1568... nexts = cycle(iter(it).next for it in iterables)
1569... while pending:
1570... try:
1571... for next in nexts:
1572... yield next()
1573... except StopIteration:
1574... pending -= 1
1575... nexts = cycle(islice(nexts, pending))
1576
1577>>> def powerset(iterable):
Raymond Hettinger68d919e2009-01-25 21:31:47 +00001578... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
1579... s = list(iterable)
1580... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001581
Raymond Hettinger44e15812009-01-02 21:26:45 +00001582>>> def unique_everseen(iterable, key=None):
1583... "List unique elements, preserving order. Remember all elements ever seen."
1584... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
1585... # unique_everseen('ABBCcAD', str.lower) --> A B C D
1586... seen = set()
1587... seen_add = seen.add
1588... if key is None:
1589... for element in iterable:
1590... if element not in seen:
1591... seen_add(element)
1592... yield element
1593... else:
1594... for element in iterable:
1595... k = key(element)
1596... if k not in seen:
1597... seen_add(k)
1598... yield element
1599
1600>>> def unique_justseen(iterable, key=None):
1601... "List unique elements, preserving order. Remember only the element just seen."
1602... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
1603... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
1604... return imap(next, imap(itemgetter(1), groupby(iterable, key)))
1605
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001606This is not part of the examples but it tests to make sure the definitions
1607perform as purported.
1608
Raymond Hettingera098b332003-09-08 23:58:40 +00001609>>> take(10, count())
1610[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1611
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001612>>> list(enumerate('abc'))
1613[(0, 'a'), (1, 'b'), (2, 'c')]
1614
1615>>> list(islice(tabulate(lambda x: 2*x), 4))
1616[0, 2, 4, 6]
1617
1618>>> nth('abcde', 3)
Raymond Hettingerd507afd2009-02-04 10:52:32 +00001619'd'
1620
1621>>> nth('abcde', 9) is None
1622True
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001623
Raymond Hettingerdbe3d282003-10-05 16:47:36 +00001624>>> quantify(xrange(99), lambda x: x%2==0)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000162550
1626
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001627>>> a = [[1, 2, 3], [4, 5, 6]]
1628>>> flatten(a)
1629[1, 2, 3, 4, 5, 6]
1630
1631>>> list(repeatfunc(pow, 5, 2, 3))
1632[8, 8, 8, 8, 8]
1633
1634>>> import random
1635>>> take(5, imap(int, repeatfunc(random.random)))
1636[0, 0, 0, 0, 0]
1637
Raymond Hettingerd591f662003-10-26 15:34:50 +00001638>>> list(pairwise('abcd'))
1639[('a', 'b'), ('b', 'c'), ('c', 'd')]
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001640
Raymond Hettingerd591f662003-10-26 15:34:50 +00001641>>> list(pairwise([]))
1642[]
1643
1644>>> list(pairwise('a'))
Raymond Hettingerbefa37d2003-06-18 19:25:37 +00001645[]
1646
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001647>>> list(islice(padnone('abc'), 0, 6))
1648['a', 'b', 'c', None, None, None]
1649
1650>>> list(ncycles('abc', 3))
1651['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
1652
1653>>> dotproduct([1,2,3], [4,5,6])
165432
1655
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001656>>> list(grouper(3, 'abcdefg', 'x'))
1657[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
1658
1659>>> list(roundrobin('abc', 'd', 'ef'))
1660['a', 'd', 'e', 'b', 'f', 'c']
1661
Raymond Hettinger68d919e2009-01-25 21:31:47 +00001662>>> list(powerset([1,2,3]))
1663[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001664
Raymond Hettinger560f9a82009-01-27 13:26:35 +00001665>>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
1666True
1667
1668>>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
1669True
1670
Raymond Hettinger44e15812009-01-02 21:26:45 +00001671>>> list(unique_everseen('AAAABBBCCDAABBB'))
1672['A', 'B', 'C', 'D']
1673
1674>>> list(unique_everseen('ABBCcAD', str.lower))
1675['A', 'B', 'C', 'D']
1676
1677>>> list(unique_justseen('AAAABBBCCDAABBB'))
1678['A', 'B', 'C', 'D', 'A', 'B']
1679
1680>>> list(unique_justseen('ABBCcAD', str.lower))
1681['A', 'B', 'C', 'A', 'D']
1682
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001683"""
1684
1685__test__ = {'libreftest' : libreftest}
1686
1687def test_main(verbose=None):
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001688 test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
Georg Brandlb84c1372007-01-21 10:28:43 +00001689 RegressionTests, LengthTransparency,
Serhiy Storchaka6c467a42013-04-06 22:51:29 +03001690 SubclassWithKwargsTest, TestExamples)
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001691 test_support.run_unittest(*test_classes)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001692
1693 # verify reference counting
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001694 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger02420702003-06-29 20:36:23 +00001695 import gc
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001696 counts = [None] * 5
1697 for i in xrange(len(counts)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001698 test_support.run_unittest(*test_classes)
Raymond Hettinger02420702003-06-29 20:36:23 +00001699 gc.collect()
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001700 counts[i] = sys.gettotalrefcount()
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001701 print counts
1702
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001703 # doctest the examples in the library reference
Raymond Hettinger929f06c2003-05-16 23:16:36 +00001704 test_support.run_doctest(sys.modules[__name__], verbose)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001705
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001706if __name__ == "__main__":
1707 test_main(verbose=True)