blob: 1bf6c5335eb7791833ca009b7f9749ee1afc2482 [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
Alex Gaynor97376482011-07-17 16:44:31 -0700140 @test_support.impl_detail("tuple reuse is specific to CPython")
141 def test_combinations_tuple_reuse(self):
Raymond Hettingerd553d852008-03-04 04:17:08 +0000142 self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
143 self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
144
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000145 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
Ezio Melottidde5b942010-02-03 05:37:26 +0000183 return fact(n+r-1) // fact(r) // fact(n-1)
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000184
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:
Ezio Melotti2623a372010-11-21 13:34:58 +0000196 self.assertEqual(result, regular_combs) # cases that should be identical
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000197 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000198 self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000199
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
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000205 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000206 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
Alex Gaynor97376482011-07-17 16:44:31 -0700211 @test_support.impl_detail("tuple reuse is specific to CPython")
212 def test_combinations_with_replacement_tuple_reuse(self):
213 cwr = combinations_with_replacement
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000214 self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
215 self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
216
Raymond Hettingerd553d852008-03-04 04:17:08 +0000217 def test_permutations(self):
218 self.assertRaises(TypeError, permutations) # too few arguments
219 self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000220 self.assertRaises(TypeError, permutations, None) # pool is not iterable
221 self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000222 self.assertEqual(list(permutations('abc', 32)), []) # r > n
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000223 self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
Raymond Hettingerd553d852008-03-04 04:17:08 +0000224 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
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000232 if r > n:
233 return
Raymond Hettingerd553d852008-03-04 04:17:08 +0000234 indices = range(n)
Raymond Hettingere70bb8d2008-03-23 00:55:46 +0000235 cycles = range(n, n-r, -1)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000236 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)]
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000262 for r in range(n+2):
Raymond Hettingerd553d852008-03-04 04:17:08 +0000263 result = list(permutations(values, r))
Ezio Melottidde5b942010-02-03 05:37:26 +0000264 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 +0000265 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
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000270 self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
Raymond Hettingerd553d852008-03-04 04:17:08 +0000271 self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000272 self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
Raymond Hettingerd553d852008-03-04 04:17:08 +0000273 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
Zachary Ware4e0df172014-04-24 13:20:27 -0500277 @test_support.impl_detail("tuple reuse is specific to CPython")
Alex Gaynor97376482011-07-17 16:44:31 -0700278 def test_permutations_tuple_reuse(self):
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000279 self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000280 self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000281
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000282 def test_combinatorics(self):
283 # Test relationships between product(), permutations(),
284 # combinations() and combinations_with_replacement().
285
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000286 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))
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000293
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000294 # Check size
Ezio Melotti2623a372010-11-21 13:34:58 +0000295 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))
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000299
300 # Check lexicographic order without repeated tuples
Ezio Melotti2623a372010-11-21 13:34:58 +0000301 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)))
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000305
306 # Check interrelationships
Ezio Melotti2623a372010-11-21 13:34:58 +0000307 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
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000309 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
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000314
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000315 def test_compress(self):
Raymond Hettinger2e2909f2009-02-19 02:15:14 +0000316 self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000317 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
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000331 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)])
Raymond Hettinger02420702003-06-29 20:36:23 +0000334 self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)])
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000335 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)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000337 self.assertRaises(TypeError, count, 2, 3, 4)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000338 self.assertRaises(TypeError, count, 'a')
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000339 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))
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000341 c = count(3)
342 self.assertEqual(repr(c), 'count(3)')
343 c.next()
344 self.assertEqual(repr(c), 'count(4)')
Jack Diederich36234e82006-09-21 17:50:26 +0000345 c = count(-9)
346 self.assertEqual(repr(c), 'count(-9)')
347 c.next()
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000348 self.assertEqual(repr(count(10.25)), 'count(10.25)')
Jack Diederich36234e82006-09-21 17:50:26 +0000349 self.assertEqual(c.next(), -8)
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000350 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 +0000351 # 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)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000355
Raymond Hettingere09f45a2009-11-30 19:44:40 +0000356 # 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
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000363 def test_count_with_stride(self):
364 self.assertEqual(zip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingera4038032009-02-14 00:25:51 +0000365 self.assertEqual(zip('abc',count(start=2,step=3)),
366 [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingeraa681c72009-02-21 07:17:22 +0000367 self.assertEqual(zip('abc',count(step=-1)),
368 [('a', 0), ('b', -1), ('c', -2)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000369 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])
Raymond Hettingeraa044612009-02-12 12:04:26 +0000374 self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
375 [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
Raymond Hettingerdbe3bfb2009-02-12 12:43:01 +0000376 self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
377 [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000378 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
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000405 def test_cycle(self):
Raymond Hettinger02420702003-06-29 20:36:23 +0000406 self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000407 self.assertEqual(list(cycle('')), [])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000408 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])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000411
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000412 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)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000418 self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000419
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
Raymond Hettinger64958a12003-12-17 20:43:33 +0000449 r = [k for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000450 self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
451 # sort s | uniq -d
Raymond Hettinger64958a12003-12-17 20:43:33 +0000452 r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000453 self.assertEqual(r, ['a', 'b', 'r'])
454 # sort s | uniq -c
Raymond Hettinger64958a12003-12-17 20:43:33 +0000455 r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000456 self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
457 # sort s | uniq -c | sort -rn | head -3
Raymond Hettinger64958a12003-12-17 20:43:33 +0000458 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000459 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
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000501 def test_ifilter(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000502 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000503 self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
Raymond Hettinger9d638372008-02-25 22:42:32 +0000504 self.assertEqual(list(ifilter(bool, [0,1,0,2,0])), [1,2])
Raymond Hettinger02420702003-06-29 20:36:23 +0000505 self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000506 self.assertRaises(TypeError, ifilter)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000507 self.assertRaises(TypeError, ifilter, lambda x:x)
508 self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000509 self.assertRaises(TypeError, ifilter, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000510 self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000511
512 def test_ifilterfalse(self):
Raymond Hettinger60eca932003-02-09 06:40:58 +0000513 self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
514 self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
Raymond Hettinger9d638372008-02-25 22:42:32 +0000515 self.assertEqual(list(ifilterfalse(bool, [0,1,0,2,0])), [0,0,0])
Raymond Hettinger02420702003-06-29 20:36:23 +0000516 self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7])
Raymond Hettinger60eca932003-02-09 06:40:58 +0000517 self.assertRaises(TypeError, ifilterfalse)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000518 self.assertRaises(TypeError, ifilterfalse, lambda x:x)
519 self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000520 self.assertRaises(TypeError, ifilterfalse, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000521 self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000522
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)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000526 self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6)))
527 self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3)))
Raymond Hettinger02420702003-06-29 20:36:23 +0000528 self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3)))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000529 self.assertEqual(list(izip('abcdef')), zip('abcdef'))
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000530 self.assertEqual(list(izip()), zip())
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000531 self.assertRaises(TypeError, izip, 3)
532 self.assertRaises(TypeError, izip, range(3), 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000533 self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
534 zip('abc', 'def'))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000535 self.assertEqual([pair for pair in izip('abc', 'def')],
536 zip('abc', 'def'))
Alex Gaynor97376482011-07-17 16:44:31 -0700537
538 @test_support.impl_detail("tuple reuse is specific to CPython")
Zachary Ware4e0df172014-04-24 13:20:27 -0500539 def test_izip_tuple_reuse(self):
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000540 ids = map(id, izip('abc', 'def'))
541 self.assertEqual(min(ids), max(ids))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000542 ids = map(id, list(izip('abc', 'def')))
543 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000544
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000545 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 ]:
Ezio Melottidde5b942010-02-03 05:37:26 +0000553 # 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)))]
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000557 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)
Tim Petersea5962f2007-03-12 18:07:52 +0000561
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000562 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'))
Tim Petersea5962f2007-03-12 18:07:52 +0000567
Ezio Melottidde5b942010-02-03 05:37:26 +0000568 self.assertEqual(list(izip_longest('abc', 'defg', **{})),
569 zip(list('abc') + [None], 'defg')) # empty keyword dict
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000570 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)",
Tim Petersea5962f2007-03-12 18:07:52 +0000575 "izip_longest('abc', fillvalue=1, bogus_keyword=None)",
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000576 ]:
577 try:
578 eval(stmt, globals(), locals())
579 except TypeError:
580 pass
581 else:
582 self.fail('Did not raise Type in: ' + stmt)
Tim Petersea5962f2007-03-12 18:07:52 +0000583
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000584 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'))
Alex Gaynor97376482011-07-17 16:44:31 -0700588
589 @test_support.impl_detail("tuple reuse is specific to CPython")
590 def test_izip_longest_tuple_reuse(self):
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000591 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
Raymond Hettingerfa7dadd2009-11-01 20:45:16 +0000596 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
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000636 def test_product(self):
637 for args, result in [
Raymond Hettingerd553d852008-03-04 04:17:08 +0000638 ([], [()]), # zero iterables
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000639 (['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)
Raymond Hettinger08ff6822008-02-29 02:21:48 +0000646 for r in range(4):
647 self.assertEqual(list(product(*(args*r))),
648 list(product(*args, **dict(repeat=r))))
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000649 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
650 self.assertRaises(TypeError, product, range(6), None)
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000651
Raymond Hettinger38fb9be2008-03-07 01:33:20 +0000652 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
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000674 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
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000683 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))]
Raymond Hettingerd553d852008-03-04 04:17:08 +0000687 expected_len = prod(map(len, args))
688 self.assertEqual(len(list(product(*args))), expected_len)
Raymond Hettinger38fb9be2008-03-07 01:33:20 +0000689 self.assertEqual(list(product(*args)), list(product1(*args)))
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000690 self.assertEqual(list(product(*args)), list(product2(*args)))
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000691 args = map(iter, args)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000692 self.assertEqual(len(list(product(*args))), expected_len)
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000693
Alex Gaynor97376482011-07-17 16:44:31 -0700694 @test_support.impl_detail("tuple reuse is specific to CPython")
695 def test_product_tuple_reuse(self):
Raymond Hettinger73d79632008-02-23 02:20:41 +0000696 self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
697 self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000698
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000699 def test_repeat(self):
Raymond Hettinger182edae2009-02-19 02:38:25 +0000700 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
Raymond Hettinger58ad2452014-06-24 21:53:45 -0700701 self.assertEqual(list(repeat(object='a', times=0)), [])
702 self.assertEqual(list(repeat(object='a', times=-1)), [])
703 self.assertEqual(list(repeat(object='a', times=-2)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000704 self.assertEqual(zip(xrange(3),repeat('a')),
705 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000706 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger02420702003-06-29 20:36:23 +0000707 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000708 self.assertEqual(list(repeat('a', 0)), [])
709 self.assertEqual(list(repeat('a', -3)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000710 self.assertRaises(TypeError, repeat)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000711 self.assertRaises(TypeError, repeat, None, 3, 4)
712 self.assertRaises(TypeError, repeat, None, 'a')
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000713 r = repeat(1+0j)
714 self.assertEqual(repr(r), 'repeat((1+0j))')
715 r = repeat(1+0j, 5)
716 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
717 list(r)
718 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000719
Raymond Hettinger58ad2452014-06-24 21:53:45 -0700720 def test_repeat_with_negative_times(self):
721 self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
722 self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
723 self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
724 self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
725
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000726 def test_imap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000727 self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
728 [0**1, 1**2, 2**3])
729 self.assertEqual(list(imap(None, 'abc', range(5))),
730 [('a',0),('b',1),('c',2)])
Raymond Hettinger02420702003-06-29 20:36:23 +0000731 self.assertEqual(list(imap(None, 'abc', count())),
732 [('a',0),('b',1),('c',2)])
733 self.assertEqual(take(2,imap(None, 'abc', count())),
734 [('a',0),('b',1)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000735 self.assertEqual(list(imap(operator.pow, [])), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000736 self.assertRaises(TypeError, imap)
737 self.assertRaises(TypeError, imap, operator.neg)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000738 self.assertRaises(TypeError, imap(10, range(5)).next)
739 self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
740 self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000741
742 def test_starmap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000743 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
744 [0**1, 1**2, 2**3])
Raymond Hettinger02420702003-06-29 20:36:23 +0000745 self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))),
746 [0**1, 1**2, 2**3])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000747 self.assertEqual(list(starmap(operator.pow, [])), [])
Raymond Hettinger47317092008-01-17 03:02:14 +0000748 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
749 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000750 self.assertRaises(TypeError, starmap)
751 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
752 self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
753 self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
754 self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000755
756 def test_islice(self):
757 for args in [ # islice(args) should agree with range(args)
758 (10, 20, 3),
759 (10, 3, 20),
760 (10, 20),
761 (10, 3),
762 (20,)
763 ]:
764 self.assertEqual(list(islice(xrange(100), *args)), range(*args))
765
766 for args, tgtargs in [ # Stop when seqn is exhausted
767 ((10, 110, 3), ((10, 100, 3))),
768 ((10, 110), ((10, 100))),
769 ((110,), (100,))
770 ]:
771 self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
772
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000773 # Test stop=None
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000774 self.assertEqual(list(islice(xrange(10), None)), range(10))
Raymond Hettingerb2594052004-12-05 09:25:51 +0000775 self.assertEqual(list(islice(xrange(10), None, None)), range(10))
776 self.assertEqual(list(islice(xrange(10), None, None, None)), range(10))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000777 self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
778 self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
779
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +0000780 # Test number of items consumed SF #1171417
781 it = iter(range(10))
782 self.assertEqual(list(islice(it, 3)), range(3))
783 self.assertEqual(list(it), range(3, 10))
784
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000785 # Test invalid arguments
Raymond Hettinger341deb72003-05-02 19:44:20 +0000786 self.assertRaises(TypeError, islice, xrange(10))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000787 self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
788 self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
789 self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
790 self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
791 self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000792 self.assertRaises(ValueError, islice, xrange(10), 'a')
793 self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
794 self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
795 self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
796 self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000797 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000798
Raymond Hettinger061bf7a2010-11-30 03:15:35 +0000799 # Issue #10323: Less islice in a predictable state
800 c = count()
801 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
802 self.assertEqual(next(c), 3)
803
Antoine Pitrou3ec903f2014-04-29 12:13:46 +0200804 # Issue #21321: check source iterator is not referenced
805 # from islice() after the latter has been exhausted
806 it = (x for x in (1, 2))
807 wr = weakref.ref(it)
808 it = islice(it, 1)
809 self.assertIsNotNone(wr())
810 list(it) # exhaust the iterator
811 self.assertIsNone(wr())
812
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000813 def test_takewhile(self):
814 data = [1, 3, 5, 20, 2, 4, 6, 8]
815 underten = lambda x: x<10
816 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000817 self.assertEqual(list(takewhile(underten, [])), [])
818 self.assertRaises(TypeError, takewhile)
819 self.assertRaises(TypeError, takewhile, operator.pow)
820 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
821 self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
822 self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000823 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
824 self.assertEqual(list(t), [1, 1, 1])
825 self.assertRaises(StopIteration, t.next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000826
827 def test_dropwhile(self):
828 data = [1, 3, 5, 20, 2, 4, 6, 8]
829 underten = lambda x: x<10
830 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000831 self.assertEqual(list(dropwhile(underten, [])), [])
832 self.assertRaises(TypeError, dropwhile)
833 self.assertRaises(TypeError, dropwhile, operator.pow)
834 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
835 self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
836 self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000837
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000838 def test_tee(self):
Raymond Hettingerad983e72003-11-12 14:32:26 +0000839 n = 200
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000840 def irange(n):
841 for i in xrange(n):
842 yield i
843
844 a, b = tee([]) # test empty iterator
845 self.assertEqual(list(a), [])
846 self.assertEqual(list(b), [])
847
848 a, b = tee(irange(n)) # test 100% interleaved
849 self.assertEqual(zip(a,b), zip(range(n),range(n)))
850
851 a, b = tee(irange(n)) # test 0% interleaved
852 self.assertEqual(list(a), range(n))
853 self.assertEqual(list(b), range(n))
854
855 a, b = tee(irange(n)) # test dealloc of leading iterator
Raymond Hettingerad983e72003-11-12 14:32:26 +0000856 for i in xrange(100):
857 self.assertEqual(a.next(), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000858 del a
859 self.assertEqual(list(b), range(n))
860
861 a, b = tee(irange(n)) # test dealloc of trailing iterator
Raymond Hettingerad983e72003-11-12 14:32:26 +0000862 for i in xrange(100):
863 self.assertEqual(a.next(), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000864 del b
Raymond Hettingerad983e72003-11-12 14:32:26 +0000865 self.assertEqual(list(a), range(100, n))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000866
867 for j in xrange(5): # test randomly interleaved
868 order = [0]*n + [1]*n
869 random.shuffle(order)
870 lists = ([], [])
871 its = tee(irange(n))
872 for i in order:
873 value = its[i].next()
874 lists[i].append(value)
875 self.assertEqual(lists[0], range(n))
876 self.assertEqual(lists[1], range(n))
877
Raymond Hettingerad983e72003-11-12 14:32:26 +0000878 # test argument format checking
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000879 self.assertRaises(TypeError, tee)
880 self.assertRaises(TypeError, tee, 3)
881 self.assertRaises(TypeError, tee, [1,2], 'x')
Raymond Hettingerad983e72003-11-12 14:32:26 +0000882 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000883
Raymond Hettingerad983e72003-11-12 14:32:26 +0000884 # tee object should be instantiable
885 a, b = tee('abc')
886 c = type(a)('def')
887 self.assertEqual(list(c), list('def'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +0000888
Raymond Hettingerad983e72003-11-12 14:32:26 +0000889 # test long-lagged and multi-way split
890 a, b, c = tee(xrange(2000), 3)
891 for i in xrange(100):
892 self.assertEqual(a.next(), i)
893 self.assertEqual(list(b), range(2000))
894 self.assertEqual([c.next(), c.next()], range(2))
895 self.assertEqual(list(a), range(100,2000))
896 self.assertEqual(list(c), range(2,2000))
897
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000898 # test values of n
899 self.assertRaises(TypeError, tee, 'abc', 'invalid')
Neal Norwitz69e88972006-09-02 02:58:13 +0000900 self.assertRaises(ValueError, tee, [], -1)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000901 for n in xrange(5):
902 result = tee('abc', n)
903 self.assertEqual(type(result), tuple)
904 self.assertEqual(len(result), n)
905 self.assertEqual(map(list, result), [list('abc')]*n)
906
Raymond Hettingerad983e72003-11-12 14:32:26 +0000907 # tee pass-through to copyable iterator
908 a, b = tee('abc')
909 c, d = tee(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000910 self.assertTrue(a is c)
Raymond Hettingerad983e72003-11-12 14:32:26 +0000911
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000912 # test tee_new
913 t1, t2 = tee('abc')
914 tnew = type(t1)
915 self.assertRaises(TypeError, tnew)
916 self.assertRaises(TypeError, tnew, 10)
917 t3 = tnew(t1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000918 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +0000919
Raymond Hettingera9f60922004-10-17 16:40:14 +0000920 # test that tee objects are weak referencable
921 a, b = tee(xrange(10))
Antoine Pitrou3ec903f2014-04-29 12:13:46 +0200922 p = weakref.proxy(a)
Raymond Hettingera9f60922004-10-17 16:40:14 +0000923 self.assertEqual(getattr(p, '__class__'), type(b))
924 del a
925 self.assertRaises(ReferenceError, getattr, p, '__class__')
926
Serhiy Storchakab09ec9b2013-01-25 13:31:05 +0200927 # Issue 13454: Crash when deleting backward iterator from tee()
928 def test_tee_del_backward(self):
Serhiy Storchaka6fef14d2013-01-26 11:51:42 +0200929 forward, backward = tee(repeat(None, 20000000))
930 any(forward) # exhaust the iterator
Serhiy Storchakab09ec9b2013-01-25 13:31:05 +0200931 del backward
932
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000933 def test_StopIteration(self):
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000934 self.assertRaises(StopIteration, izip().next)
935
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000936 for f in (chain, cycle, izip, groupby):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000937 self.assertRaises(StopIteration, f([]).next)
938 self.assertRaises(StopIteration, f(StopNow()).next)
939
940 self.assertRaises(StopIteration, islice([], None).next)
941 self.assertRaises(StopIteration, islice(StopNow(), None).next)
942
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000943 p, q = tee([])
944 self.assertRaises(StopIteration, p.next)
945 self.assertRaises(StopIteration, q.next)
946 p, q = tee(StopNow())
947 self.assertRaises(StopIteration, p.next)
948 self.assertRaises(StopIteration, q.next)
949
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000950 self.assertRaises(StopIteration, repeat(None, 0).next)
951
952 for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
953 self.assertRaises(StopIteration, f(lambda x:x, []).next)
954 self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
955
Raymond Hettingerad47fa12008-03-06 20:52:01 +0000956class TestExamples(unittest.TestCase):
957
958 def test_chain(self):
959 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
960
961 def test_chain_from_iterable(self):
962 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
963
964 def test_combinations(self):
965 self.assertEqual(list(combinations('ABCD', 2)),
966 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
967 self.assertEqual(list(combinations(range(4), 3)),
968 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
969
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000970 def test_combinations_with_replacement(self):
971 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
972 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
973
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000974 def test_compress(self):
975 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
976
Raymond Hettingerad47fa12008-03-06 20:52:01 +0000977 def test_count(self):
978 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
979
980 def test_cycle(self):
981 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
982
983 def test_dropwhile(self):
984 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
985
986 def test_groupby(self):
987 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
988 list('ABCDAB'))
989 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
990 [list('AAAA'), list('BBB'), list('CC'), list('D')])
991
992 def test_ifilter(self):
993 self.assertEqual(list(ifilter(lambda x: x%2, range(10))), [1,3,5,7,9])
994
995 def test_ifilterfalse(self):
996 self.assertEqual(list(ifilterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
997
998 def test_imap(self):
999 self.assertEqual(list(imap(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
1000
1001 def test_islice(self):
1002 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
1003 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
1004 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
1005 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1006
1007 def test_izip(self):
1008 self.assertEqual(list(izip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
1009
1010 def test_izip_longest(self):
1011 self.assertEqual(list(izip_longest('ABCD', 'xy', fillvalue='-')),
1012 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
1013
1014 def test_permutations(self):
1015 self.assertEqual(list(permutations('ABCD', 2)),
1016 map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split()))
1017 self.assertEqual(list(permutations(range(3))),
1018 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
1019
1020 def test_product(self):
1021 self.assertEqual(list(product('ABCD', 'xy')),
1022 map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split()))
1023 self.assertEqual(list(product(range(2), repeat=3)),
1024 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1025 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1026
1027 def test_repeat(self):
1028 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1029
1030 def test_stapmap(self):
1031 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1032 [32, 9, 1000])
1033
1034 def test_takewhile(self):
1035 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1036
1037
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001038class TestGC(unittest.TestCase):
1039
1040 def makecycle(self, iterator, container):
1041 container.append(iterator)
1042 iterator.next()
1043 del container, iterator
1044
1045 def test_chain(self):
1046 a = []
1047 self.makecycle(chain(a), a)
1048
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001049 def test_chain_from_iterable(self):
1050 a = []
1051 self.makecycle(chain.from_iterable([a]), a)
1052
1053 def test_combinations(self):
1054 a = []
1055 self.makecycle(combinations([1,2,a,3], 3), a)
1056
Raymond Hettingerd081abc2009-01-27 02:58:49 +00001057 def test_combinations_with_replacement(self):
1058 a = []
1059 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1060
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001061 def test_compress(self):
1062 a = []
1063 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1064
Raymond Hettingerb21d8102009-02-16 20:39:12 +00001065 def test_count(self):
1066 a = []
1067 Int = type('Int', (int,), dict(x=a))
1068 self.makecycle(count(Int(0), Int(1)), a)
1069
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001070 def test_cycle(self):
1071 a = []
1072 self.makecycle(cycle([a]*2), a)
1073
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001074 def test_dropwhile(self):
1075 a = []
1076 self.makecycle(dropwhile(bool, [0, a, a]), a)
1077
1078 def test_groupby(self):
1079 a = []
1080 self.makecycle(groupby([a]*2, lambda x:x), a)
1081
Raymond Hettingera1ca94a2008-03-06 22:51:36 +00001082 def test_issue2246(self):
1083 # Issue 2246 -- the _grouper iterator was not included in GC
1084 n = 10
1085 keyfunc = lambda x: x
1086 for i, j in groupby(xrange(n), key=keyfunc):
1087 keyfunc.__dict__.setdefault('x',[]).append(j)
1088
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001089 def test_ifilter(self):
1090 a = []
1091 self.makecycle(ifilter(lambda x:True, [a]*2), a)
1092
1093 def test_ifilterfalse(self):
1094 a = []
1095 self.makecycle(ifilterfalse(lambda x:False, a), a)
1096
1097 def test_izip(self):
1098 a = []
1099 self.makecycle(izip([a]*2, [a]*3), a)
1100
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001101 def test_izip_longest(self):
1102 a = []
1103 self.makecycle(izip_longest([a]*2, [a]*3), a)
1104 b = [a, None]
1105 self.makecycle(izip_longest([a]*2, [a]*3, fillvalue=b), a)
1106
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001107 def test_imap(self):
1108 a = []
1109 self.makecycle(imap(lambda x:x, [a]*2), a)
1110
1111 def test_islice(self):
1112 a = []
1113 self.makecycle(islice([a]*2, None), a)
1114
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001115 def test_permutations(self):
1116 a = []
1117 self.makecycle(permutations([1,2,a,3], 3), a)
1118
1119 def test_product(self):
1120 a = []
1121 self.makecycle(product([1,2,a,3], repeat=3), a)
1122
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001123 def test_repeat(self):
1124 a = []
1125 self.makecycle(repeat(a), a)
1126
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001127 def test_starmap(self):
1128 a = []
1129 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1130
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001131 def test_takewhile(self):
1132 a = []
1133 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1134
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001135def R(seqn):
1136 'Regular generator'
1137 for i in seqn:
1138 yield i
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001139
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001140class G:
1141 'Sequence using __getitem__'
1142 def __init__(self, seqn):
1143 self.seqn = seqn
1144 def __getitem__(self, i):
1145 return self.seqn[i]
1146
1147class I:
1148 'Sequence using iterator protocol'
1149 def __init__(self, seqn):
1150 self.seqn = seqn
1151 self.i = 0
1152 def __iter__(self):
1153 return self
1154 def next(self):
1155 if self.i >= len(self.seqn): raise StopIteration
1156 v = self.seqn[self.i]
1157 self.i += 1
1158 return v
1159
1160class Ig:
1161 'Sequence using iterator protocol defined with a generator'
1162 def __init__(self, seqn):
1163 self.seqn = seqn
1164 self.i = 0
1165 def __iter__(self):
1166 for val in self.seqn:
1167 yield val
1168
1169class X:
1170 'Missing __getitem__ and __iter__'
1171 def __init__(self, seqn):
1172 self.seqn = seqn
1173 self.i = 0
1174 def next(self):
1175 if self.i >= len(self.seqn): raise StopIteration
1176 v = self.seqn[self.i]
1177 self.i += 1
1178 return v
1179
1180class N:
1181 'Iterator missing next()'
1182 def __init__(self, seqn):
1183 self.seqn = seqn
1184 self.i = 0
1185 def __iter__(self):
1186 return self
1187
1188class E:
1189 'Test propagation of exceptions'
1190 def __init__(self, seqn):
1191 self.seqn = seqn
1192 self.i = 0
1193 def __iter__(self):
1194 return self
1195 def next(self):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +00001196 3 // 0
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001197
1198class S:
1199 'Test immediate stop'
1200 def __init__(self, seqn):
1201 pass
1202 def __iter__(self):
1203 return self
1204 def next(self):
1205 raise StopIteration
1206
1207def L(seqn):
1208 'Test multiple tiers of iterators'
1209 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
1210
1211
1212class TestVariousIteratorArgs(unittest.TestCase):
1213
1214 def test_chain(self):
1215 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1216 for g in (G, I, Ig, S, L, R):
1217 self.assertEqual(list(chain(g(s))), list(g(s)))
1218 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
Raymond Hettinger05bf6332008-02-28 22:30:42 +00001219 self.assertRaises(TypeError, list, chain(X(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001220 self.assertRaises(TypeError, list, chain(N(s)))
1221 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
1222
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001223 def test_compress(self):
1224 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1225 n = len(s)
1226 for g in (G, I, Ig, S, L, R):
1227 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
1228 self.assertRaises(TypeError, compress, X(s), repeat(1))
1229 self.assertRaises(TypeError, list, compress(N(s), repeat(1)))
1230 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
1231
Raymond Hettinger50986cc2008-02-22 03:16:42 +00001232 def test_product(self):
1233 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1234 self.assertRaises(TypeError, product, X(s))
1235 self.assertRaises(TypeError, product, N(s))
1236 self.assertRaises(ZeroDivisionError, product, E(s))
1237
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001238 def test_cycle(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 tgtlen = len(s) * 3
1242 expected = list(g(s))*3
1243 actual = list(islice(cycle(g(s)), tgtlen))
1244 self.assertEqual(actual, expected)
1245 self.assertRaises(TypeError, cycle, X(s))
1246 self.assertRaises(TypeError, list, cycle(N(s)))
1247 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
1248
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001249 def test_groupby(self):
1250 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1251 for g in (G, I, Ig, S, L, R):
1252 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
1253 self.assertRaises(TypeError, groupby, X(s))
1254 self.assertRaises(TypeError, list, groupby(N(s)))
1255 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
1256
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001257 def test_ifilter(self):
1258 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1259 for g in (G, I, Ig, S, L, R):
1260 self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
1261 self.assertRaises(TypeError, ifilter, isEven, X(s))
1262 self.assertRaises(TypeError, list, ifilter(isEven, N(s)))
1263 self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
1264
1265 def test_ifilterfalse(self):
1266 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1267 for g in (G, I, Ig, S, L, R):
1268 self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
1269 self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
1270 self.assertRaises(TypeError, list, ifilterfalse(isEven, N(s)))
1271 self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
1272
1273 def test_izip(self):
1274 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1275 for g in (G, I, Ig, S, L, R):
1276 self.assertEqual(list(izip(g(s))), zip(g(s)))
1277 self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s)))
1278 self.assertRaises(TypeError, izip, X(s))
1279 self.assertRaises(TypeError, list, izip(N(s)))
1280 self.assertRaises(ZeroDivisionError, list, izip(E(s)))
1281
Raymond Hettingerd36862c2007-02-21 05:20:38 +00001282 def test_iziplongest(self):
1283 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1284 for g in (G, I, Ig, S, L, R):
1285 self.assertEqual(list(izip_longest(g(s))), zip(g(s)))
1286 self.assertEqual(list(izip_longest(g(s), g(s))), zip(g(s), g(s)))
1287 self.assertRaises(TypeError, izip_longest, X(s))
1288 self.assertRaises(TypeError, list, izip_longest(N(s)))
1289 self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
1290
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001291 def test_imap(self):
1292 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1293 for g in (G, I, Ig, S, L, R):
1294 self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
1295 self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
1296 self.assertRaises(TypeError, imap, onearg, X(s))
1297 self.assertRaises(TypeError, list, imap(onearg, N(s)))
1298 self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
1299
1300 def test_islice(self):
1301 for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1302 for g in (G, I, Ig, S, L, R):
1303 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
1304 self.assertRaises(TypeError, islice, X(s), 10)
1305 self.assertRaises(TypeError, list, islice(N(s), 10))
1306 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
1307
1308 def test_starmap(self):
1309 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1310 for g in (G, I, Ig, S, L, R):
1311 ss = zip(s, s)
1312 self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
1313 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
1314 self.assertRaises(TypeError, list, starmap(operator.pow, N(ss)))
1315 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
1316
1317 def test_takewhile(self):
1318 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1319 for g in (G, I, Ig, S, L, R):
1320 tgt = []
1321 for elem in g(s):
1322 if not isEven(elem): break
1323 tgt.append(elem)
1324 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
1325 self.assertRaises(TypeError, takewhile, isEven, X(s))
1326 self.assertRaises(TypeError, list, takewhile(isEven, N(s)))
1327 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
1328
1329 def test_dropwhile(self):
1330 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1331 for g in (G, I, Ig, S, L, R):
1332 tgt = []
1333 for elem in g(s):
1334 if not tgt and isOdd(elem): continue
1335 tgt.append(elem)
1336 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
1337 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
1338 self.assertRaises(TypeError, list, dropwhile(isOdd, N(s)))
1339 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
1340
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001341 def test_tee(self):
1342 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1343 for g in (G, I, Ig, S, L, R):
1344 it1, it2 = tee(g(s))
1345 self.assertEqual(list(it1), list(g(s)))
1346 self.assertEqual(list(it2), list(g(s)))
1347 self.assertRaises(TypeError, tee, X(s))
1348 self.assertRaises(TypeError, list, tee(N(s))[0])
1349 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
1350
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001351class LengthTransparency(unittest.TestCase):
1352
1353 def test_repeat(self):
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001354 from test.test_iterlen import len
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001355 self.assertEqual(len(repeat(None, 50)), 50)
1356 self.assertRaises(TypeError, len, repeat(None))
1357
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001358class RegressionTests(unittest.TestCase):
1359
1360 def test_sf_793826(self):
1361 # Fix Armin Rigo's successful efforts to wreak havoc
1362
1363 def mutatingtuple(tuple1, f, tuple2):
1364 # this builds a tuple t which is a copy of tuple1,
1365 # then calls f(t), then mutates t to be equal to tuple2
1366 # (needs len(tuple1) == len(tuple2)).
1367 def g(value, first=[1]):
1368 if first:
1369 del first[:]
1370 f(z.next())
1371 return value
1372 items = list(tuple2)
1373 items[1:1] = list(tuple1)
1374 gen = imap(g, items)
1375 z = izip(*[gen]*len(tuple1))
1376 z.next()
1377
1378 def f(t):
1379 global T
1380 T = t
1381 first[:] = list(T)
1382
1383 first = []
1384 mutatingtuple((1,2,3), f, (4,5,6))
1385 second = list(T)
1386 self.assertEqual(first, second)
1387
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001388
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001389 def test_sf_950057(self):
1390 # Make sure that chain() and cycle() catch exceptions immediately
1391 # rather than when shifting between input sources
1392
1393 def gen1():
1394 hist.append(0)
1395 yield 1
1396 hist.append(1)
Tim Petersbeb7c0c2004-07-18 17:34:03 +00001397 raise AssertionError
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001398 hist.append(2)
1399
1400 def gen2(x):
1401 hist.append(3)
1402 yield 2
1403 hist.append(4)
1404 if x:
1405 raise StopIteration
1406
1407 hist = []
1408 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
1409 self.assertEqual(hist, [0,1])
1410
1411 hist = []
1412 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
1413 self.assertEqual(hist, [0,1])
1414
1415 hist = []
1416 self.assertRaises(AssertionError, list, cycle(gen1()))
1417 self.assertEqual(hist, [0,1])
1418
Georg Brandlb84c1372007-01-21 10:28:43 +00001419class SubclassWithKwargsTest(unittest.TestCase):
1420 def test_keywords_in_subclass(self):
1421 # count is not subclassable...
1422 for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap,
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001423 starmap, islice, takewhile, dropwhile, cycle, compress):
Georg Brandlb84c1372007-01-21 10:28:43 +00001424 class Subclass(cls):
1425 def __init__(self, newarg=None, *args):
1426 cls.__init__(self, *args)
1427 try:
1428 Subclass(newarg=1)
1429 except TypeError, err:
1430 # we expect type errors because of wrong argument count
Ezio Melottiaa980582010-01-23 23:04:36 +00001431 self.assertNotIn("does not take keyword arguments", err.args[0])
Georg Brandlb84c1372007-01-21 10:28:43 +00001432
1433
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001434libreftest = """ Doctest for examples in the library reference: libitertools.tex
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001435
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001436
1437>>> amounts = [120.15, 764.05, 823.14]
1438>>> for checknum, amount in izip(count(1200), amounts):
1439... print 'Check %d is for $%.2f' % (checknum, amount)
1440...
1441Check 1200 is for $120.15
1442Check 1201 is for $764.05
1443Check 1202 is for $823.14
1444
1445>>> import operator
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001446>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
1447... print cube
1448...
14491
14508
145127
1452
1453>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
Raymond Hettinger3567a872003-06-28 05:44:36 +00001454>>> for name in islice(reportlines, 3, None, 2):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001455... print name.title()
1456...
1457Alex
1458Laura
1459Martin
1460Walter
1461Samuele
1462
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001463>>> from operator import itemgetter
1464>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Armin Rigoa3f09272006-05-28 19:13:17 +00001465>>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001466>>> for k, g in groupby(di, itemgetter(1)):
1467... print k, map(itemgetter(0), g)
1468...
14691 ['a', 'c', 'e']
14702 ['b', 'd', 'f']
14713 ['g']
1472
Raymond Hettinger734fb572004-01-20 20:04:40 +00001473# Find runs of consecutive numbers using groupby. The key to the solution
1474# is differencing with a range so that consecutive numbers all appear in
1475# same group.
1476>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
Ezio Melottidde5b942010-02-03 05:37:26 +00001477>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Raymond Hettinger734fb572004-01-20 20:04:40 +00001478... print map(operator.itemgetter(1), g)
1479...
1480[1]
1481[4, 5, 6]
1482[10]
1483[15, 16, 17, 18]
1484[22]
1485[25, 26, 27, 28]
1486
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001487>>> def take(n, iterable):
1488... "Return first n items of the iterable as a list"
1489... return list(islice(iterable, n))
Raymond Hettingera098b332003-09-08 23:58:40 +00001490
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001491>>> def enumerate(iterable, start=0):
1492... return izip(count(start), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001493
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001494>>> def tabulate(function, start=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001495... "Return function(0), function(1), ..."
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001496... return imap(function, count(start))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001497
Raymond Hettingerf9bce832009-02-19 05:34:35 +00001498>>> def nth(iterable, n, default=None):
1499... "Returns the nth item or a default value"
1500... return next(islice(iterable, n, None), default)
Raymond Hettinger60eca932003-02-09 06:40:58 +00001501
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001502>>> def quantify(iterable, pred=bool):
1503... "Count how many times the predicate is true"
1504... return sum(imap(pred, iterable))
Raymond Hettinger60eca932003-02-09 06:40:58 +00001505
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001506>>> def padnone(iterable):
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001507... "Returns the sequence elements and then returns None indefinitely"
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001508... return chain(iterable, repeat(None))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001509
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001510>>> def ncycles(iterable, n):
Ezio Melottic2077b02011-03-16 12:34:31 +02001511... "Returns the sequence elements n times"
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001512... return chain(*repeat(iterable, n))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001513
1514>>> def dotproduct(vec1, vec2):
1515... return sum(imap(operator.mul, vec1, vec2))
1516
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001517>>> def flatten(listOfLists):
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001518... return list(chain.from_iterable(listOfLists))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001519
1520>>> def repeatfunc(func, times=None, *args):
1521... "Repeat calls to func with specified arguments."
1522... " Example: repeatfunc(random.random)"
1523... if times is None:
1524... return starmap(func, repeat(args))
1525... else:
1526... return starmap(func, repeat(args, times))
1527
Raymond Hettingerd591f662003-10-26 15:34:50 +00001528>>> def pairwise(iterable):
1529... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1530... a, b = tee(iterable)
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001531... for elem in b:
1532... break
Raymond Hettingerad983e72003-11-12 14:32:26 +00001533... return izip(a, b)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001534
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001535>>> def grouper(n, iterable, fillvalue=None):
Raymond Hettingerefdf7062008-07-30 07:27:30 +00001536... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001537... args = [iter(iterable)] * n
Raymond Hettingerf080e6d2008-07-31 01:19:50 +00001538... return izip_longest(fillvalue=fillvalue, *args)
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001539
1540>>> def roundrobin(*iterables):
Raymond Hettingerefdf7062008-07-30 07:27:30 +00001541... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001542... # Recipe credited to George Sakkis
1543... pending = len(iterables)
1544... nexts = cycle(iter(it).next for it in iterables)
1545... while pending:
1546... try:
1547... for next in nexts:
1548... yield next()
1549... except StopIteration:
1550... pending -= 1
1551... nexts = cycle(islice(nexts, pending))
1552
1553>>> def powerset(iterable):
Raymond Hettinger68d919e2009-01-25 21:31:47 +00001554... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
1555... s = list(iterable)
1556... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001557
Raymond Hettinger44e15812009-01-02 21:26:45 +00001558>>> def unique_everseen(iterable, key=None):
1559... "List unique elements, preserving order. Remember all elements ever seen."
1560... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
1561... # unique_everseen('ABBCcAD', str.lower) --> A B C D
1562... seen = set()
1563... seen_add = seen.add
1564... if key is None:
1565... for element in iterable:
1566... if element not in seen:
1567... seen_add(element)
1568... yield element
1569... else:
1570... for element in iterable:
1571... k = key(element)
1572... if k not in seen:
1573... seen_add(k)
1574... yield element
1575
1576>>> def unique_justseen(iterable, key=None):
1577... "List unique elements, preserving order. Remember only the element just seen."
1578... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
1579... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
1580... return imap(next, imap(itemgetter(1), groupby(iterable, key)))
1581
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001582This is not part of the examples but it tests to make sure the definitions
1583perform as purported.
1584
Raymond Hettingera098b332003-09-08 23:58:40 +00001585>>> take(10, count())
1586[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1587
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001588>>> list(enumerate('abc'))
1589[(0, 'a'), (1, 'b'), (2, 'c')]
1590
1591>>> list(islice(tabulate(lambda x: 2*x), 4))
1592[0, 2, 4, 6]
1593
1594>>> nth('abcde', 3)
Raymond Hettingerd507afd2009-02-04 10:52:32 +00001595'd'
1596
1597>>> nth('abcde', 9) is None
1598True
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001599
Raymond Hettingerdbe3d282003-10-05 16:47:36 +00001600>>> quantify(xrange(99), lambda x: x%2==0)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000160150
1602
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001603>>> a = [[1, 2, 3], [4, 5, 6]]
1604>>> flatten(a)
1605[1, 2, 3, 4, 5, 6]
1606
1607>>> list(repeatfunc(pow, 5, 2, 3))
1608[8, 8, 8, 8, 8]
1609
1610>>> import random
1611>>> take(5, imap(int, repeatfunc(random.random)))
1612[0, 0, 0, 0, 0]
1613
Raymond Hettingerd591f662003-10-26 15:34:50 +00001614>>> list(pairwise('abcd'))
1615[('a', 'b'), ('b', 'c'), ('c', 'd')]
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001616
Raymond Hettingerd591f662003-10-26 15:34:50 +00001617>>> list(pairwise([]))
1618[]
1619
1620>>> list(pairwise('a'))
Raymond Hettingerbefa37d2003-06-18 19:25:37 +00001621[]
1622
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001623>>> list(islice(padnone('abc'), 0, 6))
1624['a', 'b', 'c', None, None, None]
1625
1626>>> list(ncycles('abc', 3))
1627['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
1628
1629>>> dotproduct([1,2,3], [4,5,6])
163032
1631
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001632>>> list(grouper(3, 'abcdefg', 'x'))
1633[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
1634
1635>>> list(roundrobin('abc', 'd', 'ef'))
1636['a', 'd', 'e', 'b', 'f', 'c']
1637
Raymond Hettinger68d919e2009-01-25 21:31:47 +00001638>>> list(powerset([1,2,3]))
1639[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001640
Raymond Hettinger560f9a82009-01-27 13:26:35 +00001641>>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
1642True
1643
1644>>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
1645True
1646
Raymond Hettinger44e15812009-01-02 21:26:45 +00001647>>> list(unique_everseen('AAAABBBCCDAABBB'))
1648['A', 'B', 'C', 'D']
1649
1650>>> list(unique_everseen('ABBCcAD', str.lower))
1651['A', 'B', 'C', 'D']
1652
1653>>> list(unique_justseen('AAAABBBCCDAABBB'))
1654['A', 'B', 'C', 'D', 'A', 'B']
1655
1656>>> list(unique_justseen('ABBCcAD', str.lower))
1657['A', 'B', 'C', 'A', 'D']
1658
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001659"""
1660
1661__test__ = {'libreftest' : libreftest}
1662
1663def test_main(verbose=None):
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001664 test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
Georg Brandlb84c1372007-01-21 10:28:43 +00001665 RegressionTests, LengthTransparency,
Serhiy Storchaka6c467a42013-04-06 22:51:29 +03001666 SubclassWithKwargsTest, TestExamples)
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001667 test_support.run_unittest(*test_classes)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001668
1669 # verify reference counting
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001670 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger02420702003-06-29 20:36:23 +00001671 import gc
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001672 counts = [None] * 5
1673 for i in xrange(len(counts)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001674 test_support.run_unittest(*test_classes)
Raymond Hettinger02420702003-06-29 20:36:23 +00001675 gc.collect()
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001676 counts[i] = sys.gettotalrefcount()
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001677 print counts
1678
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001679 # doctest the examples in the library reference
Raymond Hettinger929f06c2003-05-16 23:16:36 +00001680 test_support.run_doctest(sys.modules[__name__], verbose)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001681
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001682if __name__ == "__main__":
1683 test_main(verbose=True)