blob: e5225f2a669cf5fda602cddbbcc1332e7b7c82f5 [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)
Serhiy Storchaka655720e2014-12-15 14:02:43 +0200361 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
362 self.assertEqual(next(pickle.loads(pickle.dumps(c, proto))), value)
Raymond Hettingere09f45a2009-11-30 19:44:40 +0000363
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000364 def test_count_with_stride(self):
365 self.assertEqual(zip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingera4038032009-02-14 00:25:51 +0000366 self.assertEqual(zip('abc',count(start=2,step=3)),
367 [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingeraa681c72009-02-21 07:17:22 +0000368 self.assertEqual(zip('abc',count(step=-1)),
369 [('a', 0), ('b', -1), ('c', -2)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000370 self.assertEqual(zip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
371 self.assertEqual(zip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
372 self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
373 self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
374 self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
Raymond Hettingeraa044612009-02-12 12:04:26 +0000375 self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
376 [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
Raymond Hettingerdbe3bfb2009-02-12 12:43:01 +0000377 self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
378 [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000379 self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
380 c = count(3, 5)
381 self.assertEqual(repr(c), 'count(3, 5)')
382 c.next()
383 self.assertEqual(repr(c), 'count(8, 5)')
384 c = count(-9, 0)
385 self.assertEqual(repr(c), 'count(-9, 0)')
386 c.next()
387 self.assertEqual(repr(c), 'count(-9, 0)')
388 c = count(-9, -3)
389 self.assertEqual(repr(c), 'count(-9, -3)')
390 c.next()
391 self.assertEqual(repr(c), 'count(-12, -3)')
392 self.assertEqual(repr(c), 'count(-12, -3)')
393 self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
394 self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int
395 self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0
396 for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
397 for j in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 1, 10, sys.maxint-5, sys.maxint+5):
398 # Test repr (ignoring the L in longs)
399 r1 = repr(count(i, j)).replace('L', '')
400 if j == 1:
401 r2 = ('count(%r)' % i).replace('L', '')
402 else:
403 r2 = ('count(%r, %r)' % (i, j)).replace('L', '')
404 self.assertEqual(r1, r2)
405
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000406 def test_cycle(self):
Raymond Hettinger02420702003-06-29 20:36:23 +0000407 self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000408 self.assertEqual(list(cycle('')), [])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000409 self.assertRaises(TypeError, cycle)
410 self.assertRaises(TypeError, cycle, 5)
411 self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000412
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000413 def test_groupby(self):
414 # Check whether it accepts arguments correctly
415 self.assertEqual([], list(groupby([])))
416 self.assertEqual([], list(groupby([], key=id)))
417 self.assertRaises(TypeError, list, groupby('abc', []))
418 self.assertRaises(TypeError, groupby, None)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000419 self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000420
421 # Check normal input
422 s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
423 (2,15,22), (3,16,23), (3,17,23)]
424 dup = []
425 for k, g in groupby(s, lambda r:r[0]):
426 for elem in g:
427 self.assertEqual(k, elem[0])
428 dup.append(elem)
429 self.assertEqual(s, dup)
430
431 # Check nested case
432 dup = []
433 for k, g in groupby(s, lambda r:r[0]):
434 for ik, ig in groupby(g, lambda r:r[2]):
435 for elem in ig:
436 self.assertEqual(k, elem[0])
437 self.assertEqual(ik, elem[2])
438 dup.append(elem)
439 self.assertEqual(s, dup)
440
441 # Check case where inner iterator is not used
442 keys = [k for k, g in groupby(s, lambda r:r[0])]
443 expectedkeys = set([r[0] for r in s])
444 self.assertEqual(set(keys), expectedkeys)
445 self.assertEqual(len(keys), len(expectedkeys))
446
447 # Exercise pipes and filters style
448 s = 'abracadabra'
449 # sort s | uniq
Raymond Hettinger64958a12003-12-17 20:43:33 +0000450 r = [k for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000451 self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
452 # sort s | uniq -d
Raymond Hettinger64958a12003-12-17 20:43:33 +0000453 r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000454 self.assertEqual(r, ['a', 'b', 'r'])
455 # sort s | uniq -c
Raymond Hettinger64958a12003-12-17 20:43:33 +0000456 r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000457 self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
458 # sort s | uniq -c | sort -rn | head -3
Raymond Hettinger64958a12003-12-17 20:43:33 +0000459 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000460 self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
461
462 # iter.next failure
463 class ExpectedError(Exception):
464 pass
465 def delayed_raise(n=0):
466 for i in range(n):
467 yield 'yo'
468 raise ExpectedError
469 def gulp(iterable, keyp=None, func=list):
470 return [func(g) for k, g in groupby(iterable, keyp)]
471
472 # iter.next failure on outer object
473 self.assertRaises(ExpectedError, gulp, delayed_raise(0))
474 # iter.next failure on inner object
475 self.assertRaises(ExpectedError, gulp, delayed_raise(1))
476
477 # __cmp__ failure
478 class DummyCmp:
479 def __cmp__(self, dst):
480 raise ExpectedError
481 s = [DummyCmp(), DummyCmp(), None]
482
483 # __cmp__ failure on outer object
484 self.assertRaises(ExpectedError, gulp, s, func=id)
485 # __cmp__ failure on inner object
486 self.assertRaises(ExpectedError, gulp, s)
487
488 # keyfunc failure
489 def keyfunc(obj):
490 if keyfunc.skip > 0:
491 keyfunc.skip -= 1
492 return obj
493 else:
494 raise ExpectedError
495
496 # keyfunc failure on outer object
497 keyfunc.skip = 0
498 self.assertRaises(ExpectedError, gulp, [None], keyfunc)
499 keyfunc.skip = 1
500 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
501
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000502 def test_ifilter(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000503 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000504 self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
Raymond Hettinger9d638372008-02-25 22:42:32 +0000505 self.assertEqual(list(ifilter(bool, [0,1,0,2,0])), [1,2])
Raymond Hettinger02420702003-06-29 20:36:23 +0000506 self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000507 self.assertRaises(TypeError, ifilter)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000508 self.assertRaises(TypeError, ifilter, lambda x:x)
509 self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000510 self.assertRaises(TypeError, ifilter, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000511 self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000512
513 def test_ifilterfalse(self):
Raymond Hettinger60eca932003-02-09 06:40:58 +0000514 self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
515 self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
Raymond Hettinger9d638372008-02-25 22:42:32 +0000516 self.assertEqual(list(ifilterfalse(bool, [0,1,0,2,0])), [0,0,0])
Raymond Hettinger02420702003-06-29 20:36:23 +0000517 self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7])
Raymond Hettinger60eca932003-02-09 06:40:58 +0000518 self.assertRaises(TypeError, ifilterfalse)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000519 self.assertRaises(TypeError, ifilterfalse, lambda x:x)
520 self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000521 self.assertRaises(TypeError, ifilterfalse, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000522 self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000523
524 def test_izip(self):
525 ans = [(x,y) for x, y in izip('abc',count())]
526 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000527 self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6)))
528 self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3)))
Raymond Hettinger02420702003-06-29 20:36:23 +0000529 self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3)))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000530 self.assertEqual(list(izip('abcdef')), zip('abcdef'))
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000531 self.assertEqual(list(izip()), zip())
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000532 self.assertRaises(TypeError, izip, 3)
533 self.assertRaises(TypeError, izip, range(3), 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000534 self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
535 zip('abc', 'def'))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000536 self.assertEqual([pair for pair in izip('abc', 'def')],
537 zip('abc', 'def'))
Alex Gaynor97376482011-07-17 16:44:31 -0700538
539 @test_support.impl_detail("tuple reuse is specific to CPython")
Zachary Ware4e0df172014-04-24 13:20:27 -0500540 def test_izip_tuple_reuse(self):
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000541 ids = map(id, izip('abc', 'def'))
542 self.assertEqual(min(ids), max(ids))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000543 ids = map(id, list(izip('abc', 'def')))
544 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000545
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000546 def test_iziplongest(self):
547 for args in [
548 ['abc', range(6)],
549 [range(6), 'abc'],
550 [range(1000), range(2000,2100), range(3000,3050)],
551 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
552 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
553 ]:
Ezio Melottidde5b942010-02-03 05:37:26 +0000554 # target = map(None, *args) <- this raises a py3k warning
555 # this is the replacement:
556 target = [tuple([arg[i] if i < len(arg) else None for arg in args])
557 for i in range(max(map(len, args)))]
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000558 self.assertEqual(list(izip_longest(*args)), target)
559 self.assertEqual(list(izip_longest(*args, **{})), target)
560 target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
561 self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target)
Tim Petersea5962f2007-03-12 18:07:52 +0000562
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000563 self.assertEqual(take(3,izip_longest('abcdef', count())), zip('abcdef', range(3))) # take 3 from infinite input
564
565 self.assertEqual(list(izip_longest()), zip())
566 self.assertEqual(list(izip_longest([])), zip([]))
567 self.assertEqual(list(izip_longest('abcdef')), zip('abcdef'))
Tim Petersea5962f2007-03-12 18:07:52 +0000568
Ezio Melottidde5b942010-02-03 05:37:26 +0000569 self.assertEqual(list(izip_longest('abc', 'defg', **{})),
570 zip(list('abc') + [None], 'defg')) # empty keyword dict
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000571 self.assertRaises(TypeError, izip_longest, 3)
572 self.assertRaises(TypeError, izip_longest, range(3), 3)
573
574 for stmt in [
575 "izip_longest('abc', fv=1)",
Tim Petersea5962f2007-03-12 18:07:52 +0000576 "izip_longest('abc', fillvalue=1, bogus_keyword=None)",
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000577 ]:
578 try:
579 eval(stmt, globals(), locals())
580 except TypeError:
581 pass
582 else:
583 self.fail('Did not raise Type in: ' + stmt)
Tim Petersea5962f2007-03-12 18:07:52 +0000584
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000585 self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')],
586 zip('abc', 'def'))
587 self.assertEqual([pair for pair in izip_longest('abc', 'def')],
588 zip('abc', 'def'))
Alex Gaynor97376482011-07-17 16:44:31 -0700589
590 @test_support.impl_detail("tuple reuse is specific to CPython")
591 def test_izip_longest_tuple_reuse(self):
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000592 ids = map(id, izip_longest('abc', 'def'))
593 self.assertEqual(min(ids), max(ids))
594 ids = map(id, list(izip_longest('abc', 'def')))
595 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
596
Raymond Hettingerfa7dadd2009-11-01 20:45:16 +0000597 def test_bug_7244(self):
598
599 class Repeater(object):
600 # this class is similar to itertools.repeat
601 def __init__(self, o, t, e):
602 self.o = o
603 self.t = int(t)
604 self.e = e
605 def __iter__(self): # its iterator is itself
606 return self
607 def next(self):
608 if self.t > 0:
609 self.t -= 1
610 return self.o
611 else:
612 raise self.e
613
614 # Formerly this code in would fail in debug mode
615 # with Undetected Error and Stop Iteration
616 r1 = Repeater(1, 3, StopIteration)
617 r2 = Repeater(2, 4, StopIteration)
618 def run(r1, r2):
619 result = []
620 for i, j in izip_longest(r1, r2, fillvalue=0):
621 with test_support.captured_output('stdout'):
622 print (i, j)
623 result.append((i, j))
624 return result
625 self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])
626
627 # Formerly, the RuntimeError would be lost
628 # and StopIteration would stop as expected
629 r1 = Repeater(1, 3, RuntimeError)
630 r2 = Repeater(2, 4, StopIteration)
631 it = izip_longest(r1, r2, fillvalue=0)
632 self.assertEqual(next(it), (1, 2))
633 self.assertEqual(next(it), (1, 2))
634 self.assertEqual(next(it), (1, 2))
635 self.assertRaises(RuntimeError, next, it)
636
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000637 def test_product(self):
638 for args, result in [
Raymond Hettingerd553d852008-03-04 04:17:08 +0000639 ([], [()]), # zero iterables
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000640 (['ab'], [('a',), ('b',)]), # one iterable
641 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
642 ([range(0), range(2), range(3)], []), # first iterable with zero length
643 ([range(2), range(0), range(3)], []), # middle iterable with zero length
644 ([range(2), range(3), range(0)], []), # last iterable with zero length
645 ]:
646 self.assertEqual(list(product(*args)), result)
Raymond Hettinger08ff6822008-02-29 02:21:48 +0000647 for r in range(4):
648 self.assertEqual(list(product(*(args*r))),
649 list(product(*args, **dict(repeat=r))))
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000650 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
651 self.assertRaises(TypeError, product, range(6), None)
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000652
Raymond Hettinger38fb9be2008-03-07 01:33:20 +0000653 def product1(*args, **kwds):
654 pools = map(tuple, args) * kwds.get('repeat', 1)
655 n = len(pools)
656 if n == 0:
657 yield ()
658 return
659 if any(len(pool) == 0 for pool in pools):
660 return
661 indices = [0] * n
662 yield tuple(pool[i] for pool, i in zip(pools, indices))
663 while 1:
664 for i in reversed(range(n)): # right to left
665 if indices[i] == len(pools[i]) - 1:
666 continue
667 indices[i] += 1
668 for j in range(i+1, n):
669 indices[j] = 0
670 yield tuple(pool[i] for pool, i in zip(pools, indices))
671 break
672 else:
673 return
674
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000675 def product2(*args, **kwds):
676 'Pure python version used in docs'
677 pools = map(tuple, args) * kwds.get('repeat', 1)
678 result = [[]]
679 for pool in pools:
680 result = [x+[y] for x in result for y in pool]
681 for prod in result:
682 yield tuple(prod)
683
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000684 argtypes = ['', 'abc', '', xrange(0), xrange(4), dict(a=1, b=2, c=3),
685 set('abcdefg'), range(11), tuple(range(13))]
686 for i in range(100):
687 args = [random.choice(argtypes) for j in range(random.randrange(5))]
Raymond Hettingerd553d852008-03-04 04:17:08 +0000688 expected_len = prod(map(len, args))
689 self.assertEqual(len(list(product(*args))), expected_len)
Raymond Hettinger38fb9be2008-03-07 01:33:20 +0000690 self.assertEqual(list(product(*args)), list(product1(*args)))
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000691 self.assertEqual(list(product(*args)), list(product2(*args)))
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000692 args = map(iter, args)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000693 self.assertEqual(len(list(product(*args))), expected_len)
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000694
Alex Gaynor97376482011-07-17 16:44:31 -0700695 @test_support.impl_detail("tuple reuse is specific to CPython")
696 def test_product_tuple_reuse(self):
Raymond Hettinger73d79632008-02-23 02:20:41 +0000697 self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
698 self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000699
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000700 def test_repeat(self):
Raymond Hettinger182edae2009-02-19 02:38:25 +0000701 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
Raymond Hettinger58ad2452014-06-24 21:53:45 -0700702 self.assertEqual(list(repeat(object='a', times=0)), [])
703 self.assertEqual(list(repeat(object='a', times=-1)), [])
704 self.assertEqual(list(repeat(object='a', times=-2)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000705 self.assertEqual(zip(xrange(3),repeat('a')),
706 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000707 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger02420702003-06-29 20:36:23 +0000708 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000709 self.assertEqual(list(repeat('a', 0)), [])
710 self.assertEqual(list(repeat('a', -3)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000711 self.assertRaises(TypeError, repeat)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000712 self.assertRaises(TypeError, repeat, None, 3, 4)
713 self.assertRaises(TypeError, repeat, None, 'a')
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000714 r = repeat(1+0j)
715 self.assertEqual(repr(r), 'repeat((1+0j))')
716 r = repeat(1+0j, 5)
717 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
718 list(r)
719 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000720
Raymond Hettinger58ad2452014-06-24 21:53:45 -0700721 def test_repeat_with_negative_times(self):
722 self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
723 self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
724 self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
725 self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
726
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000727 def test_imap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000728 self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
729 [0**1, 1**2, 2**3])
730 self.assertEqual(list(imap(None, 'abc', range(5))),
731 [('a',0),('b',1),('c',2)])
Raymond Hettinger02420702003-06-29 20:36:23 +0000732 self.assertEqual(list(imap(None, 'abc', count())),
733 [('a',0),('b',1),('c',2)])
734 self.assertEqual(take(2,imap(None, 'abc', count())),
735 [('a',0),('b',1)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000736 self.assertEqual(list(imap(operator.pow, [])), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000737 self.assertRaises(TypeError, imap)
738 self.assertRaises(TypeError, imap, operator.neg)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000739 self.assertRaises(TypeError, imap(10, range(5)).next)
740 self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
741 self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000742
743 def test_starmap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000744 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
745 [0**1, 1**2, 2**3])
Raymond Hettinger02420702003-06-29 20:36:23 +0000746 self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))),
747 [0**1, 1**2, 2**3])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000748 self.assertEqual(list(starmap(operator.pow, [])), [])
Raymond Hettinger47317092008-01-17 03:02:14 +0000749 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
750 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000751 self.assertRaises(TypeError, starmap)
752 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
753 self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
754 self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
755 self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000756
757 def test_islice(self):
758 for args in [ # islice(args) should agree with range(args)
759 (10, 20, 3),
760 (10, 3, 20),
761 (10, 20),
762 (10, 3),
763 (20,)
764 ]:
765 self.assertEqual(list(islice(xrange(100), *args)), range(*args))
766
767 for args, tgtargs in [ # Stop when seqn is exhausted
768 ((10, 110, 3), ((10, 100, 3))),
769 ((10, 110), ((10, 100))),
770 ((110,), (100,))
771 ]:
772 self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
773
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000774 # Test stop=None
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000775 self.assertEqual(list(islice(xrange(10), None)), range(10))
Raymond Hettingerb2594052004-12-05 09:25:51 +0000776 self.assertEqual(list(islice(xrange(10), None, None)), range(10))
777 self.assertEqual(list(islice(xrange(10), None, None, None)), range(10))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000778 self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
779 self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
780
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +0000781 # Test number of items consumed SF #1171417
782 it = iter(range(10))
783 self.assertEqual(list(islice(it, 3)), range(3))
784 self.assertEqual(list(it), range(3, 10))
785
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000786 # Test invalid arguments
Raymond Hettinger341deb72003-05-02 19:44:20 +0000787 self.assertRaises(TypeError, islice, xrange(10))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000788 self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
789 self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
790 self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
791 self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
792 self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000793 self.assertRaises(ValueError, islice, xrange(10), 'a')
794 self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
795 self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
796 self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
797 self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000798 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000799
Raymond Hettinger061bf7a2010-11-30 03:15:35 +0000800 # Issue #10323: Less islice in a predictable state
801 c = count()
802 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
803 self.assertEqual(next(c), 3)
804
Antoine Pitrou3ec903f2014-04-29 12:13:46 +0200805 # Issue #21321: check source iterator is not referenced
806 # from islice() after the latter has been exhausted
807 it = (x for x in (1, 2))
808 wr = weakref.ref(it)
809 it = islice(it, 1)
810 self.assertIsNotNone(wr())
811 list(it) # exhaust the iterator
Benjamin Petersonec9d5472014-08-24 18:07:28 -0500812 test_support.gc_collect()
Antoine Pitrou3ec903f2014-04-29 12:13:46 +0200813 self.assertIsNone(wr())
814
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000815 def test_takewhile(self):
816 data = [1, 3, 5, 20, 2, 4, 6, 8]
817 underten = lambda x: x<10
818 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000819 self.assertEqual(list(takewhile(underten, [])), [])
820 self.assertRaises(TypeError, takewhile)
821 self.assertRaises(TypeError, takewhile, operator.pow)
822 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
823 self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
824 self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000825 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
826 self.assertEqual(list(t), [1, 1, 1])
827 self.assertRaises(StopIteration, t.next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000828
829 def test_dropwhile(self):
830 data = [1, 3, 5, 20, 2, 4, 6, 8]
831 underten = lambda x: x<10
832 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000833 self.assertEqual(list(dropwhile(underten, [])), [])
834 self.assertRaises(TypeError, dropwhile)
835 self.assertRaises(TypeError, dropwhile, operator.pow)
836 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
837 self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
838 self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000839
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000840 def test_tee(self):
Raymond Hettingerad983e72003-11-12 14:32:26 +0000841 n = 200
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000842 def irange(n):
843 for i in xrange(n):
844 yield i
845
846 a, b = tee([]) # test empty iterator
847 self.assertEqual(list(a), [])
848 self.assertEqual(list(b), [])
849
850 a, b = tee(irange(n)) # test 100% interleaved
851 self.assertEqual(zip(a,b), zip(range(n),range(n)))
852
853 a, b = tee(irange(n)) # test 0% interleaved
854 self.assertEqual(list(a), range(n))
855 self.assertEqual(list(b), range(n))
856
857 a, b = tee(irange(n)) # test dealloc of leading iterator
Raymond Hettingerad983e72003-11-12 14:32:26 +0000858 for i in xrange(100):
859 self.assertEqual(a.next(), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000860 del a
861 self.assertEqual(list(b), range(n))
862
863 a, b = tee(irange(n)) # test dealloc of trailing iterator
Raymond Hettingerad983e72003-11-12 14:32:26 +0000864 for i in xrange(100):
865 self.assertEqual(a.next(), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000866 del b
Raymond Hettingerad983e72003-11-12 14:32:26 +0000867 self.assertEqual(list(a), range(100, n))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000868
869 for j in xrange(5): # test randomly interleaved
870 order = [0]*n + [1]*n
871 random.shuffle(order)
872 lists = ([], [])
873 its = tee(irange(n))
874 for i in order:
875 value = its[i].next()
876 lists[i].append(value)
877 self.assertEqual(lists[0], range(n))
878 self.assertEqual(lists[1], range(n))
879
Raymond Hettingerad983e72003-11-12 14:32:26 +0000880 # test argument format checking
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000881 self.assertRaises(TypeError, tee)
882 self.assertRaises(TypeError, tee, 3)
883 self.assertRaises(TypeError, tee, [1,2], 'x')
Raymond Hettingerad983e72003-11-12 14:32:26 +0000884 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000885
Raymond Hettingerad983e72003-11-12 14:32:26 +0000886 # tee object should be instantiable
887 a, b = tee('abc')
888 c = type(a)('def')
889 self.assertEqual(list(c), list('def'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +0000890
Raymond Hettingerad983e72003-11-12 14:32:26 +0000891 # test long-lagged and multi-way split
892 a, b, c = tee(xrange(2000), 3)
893 for i in xrange(100):
894 self.assertEqual(a.next(), i)
895 self.assertEqual(list(b), range(2000))
896 self.assertEqual([c.next(), c.next()], range(2))
897 self.assertEqual(list(a), range(100,2000))
898 self.assertEqual(list(c), range(2,2000))
899
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000900 # test values of n
901 self.assertRaises(TypeError, tee, 'abc', 'invalid')
Neal Norwitz69e88972006-09-02 02:58:13 +0000902 self.assertRaises(ValueError, tee, [], -1)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000903 for n in xrange(5):
904 result = tee('abc', n)
905 self.assertEqual(type(result), tuple)
906 self.assertEqual(len(result), n)
907 self.assertEqual(map(list, result), [list('abc')]*n)
908
Raymond Hettingerad983e72003-11-12 14:32:26 +0000909 # tee pass-through to copyable iterator
910 a, b = tee('abc')
911 c, d = tee(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000912 self.assertTrue(a is c)
Raymond Hettingerad983e72003-11-12 14:32:26 +0000913
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000914 # test tee_new
915 t1, t2 = tee('abc')
916 tnew = type(t1)
917 self.assertRaises(TypeError, tnew)
918 self.assertRaises(TypeError, tnew, 10)
919 t3 = tnew(t1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000920 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +0000921
Raymond Hettingera9f60922004-10-17 16:40:14 +0000922 # test that tee objects are weak referencable
923 a, b = tee(xrange(10))
Antoine Pitrou3ec903f2014-04-29 12:13:46 +0200924 p = weakref.proxy(a)
Raymond Hettingera9f60922004-10-17 16:40:14 +0000925 self.assertEqual(getattr(p, '__class__'), type(b))
926 del a
927 self.assertRaises(ReferenceError, getattr, p, '__class__')
928
Serhiy Storchakab09ec9b2013-01-25 13:31:05 +0200929 # Issue 13454: Crash when deleting backward iterator from tee()
930 def test_tee_del_backward(self):
Serhiy Storchaka6fef14d2013-01-26 11:51:42 +0200931 forward, backward = tee(repeat(None, 20000000))
932 any(forward) # exhaust the iterator
Serhiy Storchakab09ec9b2013-01-25 13:31:05 +0200933 del backward
934
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000935 def test_StopIteration(self):
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000936 self.assertRaises(StopIteration, izip().next)
937
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000938 for f in (chain, cycle, izip, groupby):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000939 self.assertRaises(StopIteration, f([]).next)
940 self.assertRaises(StopIteration, f(StopNow()).next)
941
942 self.assertRaises(StopIteration, islice([], None).next)
943 self.assertRaises(StopIteration, islice(StopNow(), None).next)
944
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000945 p, q = tee([])
946 self.assertRaises(StopIteration, p.next)
947 self.assertRaises(StopIteration, q.next)
948 p, q = tee(StopNow())
949 self.assertRaises(StopIteration, p.next)
950 self.assertRaises(StopIteration, q.next)
951
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000952 self.assertRaises(StopIteration, repeat(None, 0).next)
953
954 for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
955 self.assertRaises(StopIteration, f(lambda x:x, []).next)
956 self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
957
Raymond Hettingerad47fa12008-03-06 20:52:01 +0000958class TestExamples(unittest.TestCase):
959
960 def test_chain(self):
961 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
962
963 def test_chain_from_iterable(self):
964 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
965
966 def test_combinations(self):
967 self.assertEqual(list(combinations('ABCD', 2)),
968 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
969 self.assertEqual(list(combinations(range(4), 3)),
970 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
971
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000972 def test_combinations_with_replacement(self):
973 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
974 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
975
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000976 def test_compress(self):
977 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
978
Raymond Hettingerad47fa12008-03-06 20:52:01 +0000979 def test_count(self):
980 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
981
982 def test_cycle(self):
983 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
984
985 def test_dropwhile(self):
986 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
987
988 def test_groupby(self):
989 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
990 list('ABCDAB'))
991 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
992 [list('AAAA'), list('BBB'), list('CC'), list('D')])
993
994 def test_ifilter(self):
995 self.assertEqual(list(ifilter(lambda x: x%2, range(10))), [1,3,5,7,9])
996
997 def test_ifilterfalse(self):
998 self.assertEqual(list(ifilterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
999
1000 def test_imap(self):
1001 self.assertEqual(list(imap(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
1002
1003 def test_islice(self):
1004 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
1005 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
1006 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
1007 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1008
1009 def test_izip(self):
1010 self.assertEqual(list(izip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
1011
1012 def test_izip_longest(self):
1013 self.assertEqual(list(izip_longest('ABCD', 'xy', fillvalue='-')),
1014 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
1015
1016 def test_permutations(self):
1017 self.assertEqual(list(permutations('ABCD', 2)),
1018 map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split()))
1019 self.assertEqual(list(permutations(range(3))),
1020 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
1021
1022 def test_product(self):
1023 self.assertEqual(list(product('ABCD', 'xy')),
1024 map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split()))
1025 self.assertEqual(list(product(range(2), repeat=3)),
1026 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1027 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1028
1029 def test_repeat(self):
1030 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1031
1032 def test_stapmap(self):
1033 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1034 [32, 9, 1000])
1035
1036 def test_takewhile(self):
1037 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1038
1039
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001040class TestGC(unittest.TestCase):
1041
1042 def makecycle(self, iterator, container):
1043 container.append(iterator)
1044 iterator.next()
1045 del container, iterator
1046
1047 def test_chain(self):
1048 a = []
1049 self.makecycle(chain(a), a)
1050
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001051 def test_chain_from_iterable(self):
1052 a = []
1053 self.makecycle(chain.from_iterable([a]), a)
1054
1055 def test_combinations(self):
1056 a = []
1057 self.makecycle(combinations([1,2,a,3], 3), a)
1058
Raymond Hettingerd081abc2009-01-27 02:58:49 +00001059 def test_combinations_with_replacement(self):
1060 a = []
1061 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1062
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001063 def test_compress(self):
1064 a = []
1065 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1066
Raymond Hettingerb21d8102009-02-16 20:39:12 +00001067 def test_count(self):
1068 a = []
1069 Int = type('Int', (int,), dict(x=a))
1070 self.makecycle(count(Int(0), Int(1)), a)
1071
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001072 def test_cycle(self):
1073 a = []
1074 self.makecycle(cycle([a]*2), a)
1075
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001076 def test_dropwhile(self):
1077 a = []
1078 self.makecycle(dropwhile(bool, [0, a, a]), a)
1079
1080 def test_groupby(self):
1081 a = []
1082 self.makecycle(groupby([a]*2, lambda x:x), a)
1083
Raymond Hettingera1ca94a2008-03-06 22:51:36 +00001084 def test_issue2246(self):
1085 # Issue 2246 -- the _grouper iterator was not included in GC
1086 n = 10
1087 keyfunc = lambda x: x
1088 for i, j in groupby(xrange(n), key=keyfunc):
1089 keyfunc.__dict__.setdefault('x',[]).append(j)
1090
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001091 def test_ifilter(self):
1092 a = []
1093 self.makecycle(ifilter(lambda x:True, [a]*2), a)
1094
1095 def test_ifilterfalse(self):
1096 a = []
1097 self.makecycle(ifilterfalse(lambda x:False, a), a)
1098
1099 def test_izip(self):
1100 a = []
1101 self.makecycle(izip([a]*2, [a]*3), a)
1102
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001103 def test_izip_longest(self):
1104 a = []
1105 self.makecycle(izip_longest([a]*2, [a]*3), a)
1106 b = [a, None]
1107 self.makecycle(izip_longest([a]*2, [a]*3, fillvalue=b), a)
1108
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001109 def test_imap(self):
1110 a = []
1111 self.makecycle(imap(lambda x:x, [a]*2), a)
1112
1113 def test_islice(self):
1114 a = []
1115 self.makecycle(islice([a]*2, None), a)
1116
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001117 def test_permutations(self):
1118 a = []
1119 self.makecycle(permutations([1,2,a,3], 3), a)
1120
1121 def test_product(self):
1122 a = []
1123 self.makecycle(product([1,2,a,3], repeat=3), a)
1124
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001125 def test_repeat(self):
1126 a = []
1127 self.makecycle(repeat(a), a)
1128
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001129 def test_starmap(self):
1130 a = []
1131 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1132
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001133 def test_takewhile(self):
1134 a = []
1135 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1136
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001137def R(seqn):
1138 'Regular generator'
1139 for i in seqn:
1140 yield i
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001141
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001142class G:
1143 'Sequence using __getitem__'
1144 def __init__(self, seqn):
1145 self.seqn = seqn
1146 def __getitem__(self, i):
1147 return self.seqn[i]
1148
1149class I:
1150 'Sequence using iterator protocol'
1151 def __init__(self, seqn):
1152 self.seqn = seqn
1153 self.i = 0
1154 def __iter__(self):
1155 return self
1156 def next(self):
1157 if self.i >= len(self.seqn): raise StopIteration
1158 v = self.seqn[self.i]
1159 self.i += 1
1160 return v
1161
1162class Ig:
1163 'Sequence using iterator protocol defined with a generator'
1164 def __init__(self, seqn):
1165 self.seqn = seqn
1166 self.i = 0
1167 def __iter__(self):
1168 for val in self.seqn:
1169 yield val
1170
1171class X:
1172 'Missing __getitem__ and __iter__'
1173 def __init__(self, seqn):
1174 self.seqn = seqn
1175 self.i = 0
1176 def next(self):
1177 if self.i >= len(self.seqn): raise StopIteration
1178 v = self.seqn[self.i]
1179 self.i += 1
1180 return v
1181
1182class N:
1183 'Iterator missing next()'
1184 def __init__(self, seqn):
1185 self.seqn = seqn
1186 self.i = 0
1187 def __iter__(self):
1188 return self
1189
1190class E:
1191 'Test propagation of exceptions'
1192 def __init__(self, seqn):
1193 self.seqn = seqn
1194 self.i = 0
1195 def __iter__(self):
1196 return self
1197 def next(self):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +00001198 3 // 0
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001199
1200class S:
1201 'Test immediate stop'
1202 def __init__(self, seqn):
1203 pass
1204 def __iter__(self):
1205 return self
1206 def next(self):
1207 raise StopIteration
1208
1209def L(seqn):
1210 'Test multiple tiers of iterators'
1211 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
1212
1213
1214class TestVariousIteratorArgs(unittest.TestCase):
1215
1216 def test_chain(self):
1217 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1218 for g in (G, I, Ig, S, L, R):
1219 self.assertEqual(list(chain(g(s))), list(g(s)))
1220 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
Raymond Hettinger05bf6332008-02-28 22:30:42 +00001221 self.assertRaises(TypeError, list, chain(X(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001222 self.assertRaises(TypeError, list, chain(N(s)))
1223 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
1224
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001225 def test_compress(self):
1226 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1227 n = len(s)
1228 for g in (G, I, Ig, S, L, R):
1229 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
1230 self.assertRaises(TypeError, compress, X(s), repeat(1))
1231 self.assertRaises(TypeError, list, compress(N(s), repeat(1)))
1232 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
1233
Raymond Hettinger50986cc2008-02-22 03:16:42 +00001234 def test_product(self):
1235 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1236 self.assertRaises(TypeError, product, X(s))
1237 self.assertRaises(TypeError, product, N(s))
1238 self.assertRaises(ZeroDivisionError, product, E(s))
1239
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001240 def test_cycle(self):
1241 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1242 for g in (G, I, Ig, S, L, R):
1243 tgtlen = len(s) * 3
1244 expected = list(g(s))*3
1245 actual = list(islice(cycle(g(s)), tgtlen))
1246 self.assertEqual(actual, expected)
1247 self.assertRaises(TypeError, cycle, X(s))
1248 self.assertRaises(TypeError, list, cycle(N(s)))
1249 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
1250
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001251 def test_groupby(self):
1252 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1253 for g in (G, I, Ig, S, L, R):
1254 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
1255 self.assertRaises(TypeError, groupby, X(s))
1256 self.assertRaises(TypeError, list, groupby(N(s)))
1257 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
1258
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001259 def test_ifilter(self):
1260 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1261 for g in (G, I, Ig, S, L, R):
1262 self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
1263 self.assertRaises(TypeError, ifilter, isEven, X(s))
1264 self.assertRaises(TypeError, list, ifilter(isEven, N(s)))
1265 self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
1266
1267 def test_ifilterfalse(self):
1268 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1269 for g in (G, I, Ig, S, L, R):
1270 self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
1271 self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
1272 self.assertRaises(TypeError, list, ifilterfalse(isEven, N(s)))
1273 self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
1274
1275 def test_izip(self):
1276 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1277 for g in (G, I, Ig, S, L, R):
1278 self.assertEqual(list(izip(g(s))), zip(g(s)))
1279 self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s)))
1280 self.assertRaises(TypeError, izip, X(s))
1281 self.assertRaises(TypeError, list, izip(N(s)))
1282 self.assertRaises(ZeroDivisionError, list, izip(E(s)))
1283
Raymond Hettingerd36862c2007-02-21 05:20:38 +00001284 def test_iziplongest(self):
1285 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1286 for g in (G, I, Ig, S, L, R):
1287 self.assertEqual(list(izip_longest(g(s))), zip(g(s)))
1288 self.assertEqual(list(izip_longest(g(s), g(s))), zip(g(s), g(s)))
1289 self.assertRaises(TypeError, izip_longest, X(s))
1290 self.assertRaises(TypeError, list, izip_longest(N(s)))
1291 self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
1292
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001293 def test_imap(self):
1294 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1295 for g in (G, I, Ig, S, L, R):
1296 self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
1297 self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
1298 self.assertRaises(TypeError, imap, onearg, X(s))
1299 self.assertRaises(TypeError, list, imap(onearg, N(s)))
1300 self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
1301
1302 def test_islice(self):
1303 for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1304 for g in (G, I, Ig, S, L, R):
1305 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
1306 self.assertRaises(TypeError, islice, X(s), 10)
1307 self.assertRaises(TypeError, list, islice(N(s), 10))
1308 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
1309
1310 def test_starmap(self):
1311 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1312 for g in (G, I, Ig, S, L, R):
1313 ss = zip(s, s)
1314 self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
1315 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
1316 self.assertRaises(TypeError, list, starmap(operator.pow, N(ss)))
1317 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
1318
1319 def test_takewhile(self):
1320 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1321 for g in (G, I, Ig, S, L, R):
1322 tgt = []
1323 for elem in g(s):
1324 if not isEven(elem): break
1325 tgt.append(elem)
1326 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
1327 self.assertRaises(TypeError, takewhile, isEven, X(s))
1328 self.assertRaises(TypeError, list, takewhile(isEven, N(s)))
1329 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
1330
1331 def test_dropwhile(self):
1332 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1333 for g in (G, I, Ig, S, L, R):
1334 tgt = []
1335 for elem in g(s):
1336 if not tgt and isOdd(elem): continue
1337 tgt.append(elem)
1338 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
1339 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
1340 self.assertRaises(TypeError, list, dropwhile(isOdd, N(s)))
1341 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
1342
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001343 def test_tee(self):
1344 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1345 for g in (G, I, Ig, S, L, R):
1346 it1, it2 = tee(g(s))
1347 self.assertEqual(list(it1), list(g(s)))
1348 self.assertEqual(list(it2), list(g(s)))
1349 self.assertRaises(TypeError, tee, X(s))
1350 self.assertRaises(TypeError, list, tee(N(s))[0])
1351 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
1352
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001353class LengthTransparency(unittest.TestCase):
1354
1355 def test_repeat(self):
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001356 from test.test_iterlen import len
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001357 self.assertEqual(len(repeat(None, 50)), 50)
1358 self.assertRaises(TypeError, len, repeat(None))
1359
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001360class RegressionTests(unittest.TestCase):
1361
1362 def test_sf_793826(self):
1363 # Fix Armin Rigo's successful efforts to wreak havoc
1364
1365 def mutatingtuple(tuple1, f, tuple2):
1366 # this builds a tuple t which is a copy of tuple1,
1367 # then calls f(t), then mutates t to be equal to tuple2
1368 # (needs len(tuple1) == len(tuple2)).
1369 def g(value, first=[1]):
1370 if first:
1371 del first[:]
1372 f(z.next())
1373 return value
1374 items = list(tuple2)
1375 items[1:1] = list(tuple1)
1376 gen = imap(g, items)
1377 z = izip(*[gen]*len(tuple1))
1378 z.next()
1379
1380 def f(t):
1381 global T
1382 T = t
1383 first[:] = list(T)
1384
1385 first = []
1386 mutatingtuple((1,2,3), f, (4,5,6))
1387 second = list(T)
1388 self.assertEqual(first, second)
1389
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001390
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001391 def test_sf_950057(self):
1392 # Make sure that chain() and cycle() catch exceptions immediately
1393 # rather than when shifting between input sources
1394
1395 def gen1():
1396 hist.append(0)
1397 yield 1
1398 hist.append(1)
Tim Petersbeb7c0c2004-07-18 17:34:03 +00001399 raise AssertionError
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001400 hist.append(2)
1401
1402 def gen2(x):
1403 hist.append(3)
1404 yield 2
1405 hist.append(4)
1406 if x:
1407 raise StopIteration
1408
1409 hist = []
1410 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
1411 self.assertEqual(hist, [0,1])
1412
1413 hist = []
1414 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
1415 self.assertEqual(hist, [0,1])
1416
1417 hist = []
1418 self.assertRaises(AssertionError, list, cycle(gen1()))
1419 self.assertEqual(hist, [0,1])
1420
Georg Brandlb84c1372007-01-21 10:28:43 +00001421class SubclassWithKwargsTest(unittest.TestCase):
1422 def test_keywords_in_subclass(self):
1423 # count is not subclassable...
1424 for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap,
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001425 starmap, islice, takewhile, dropwhile, cycle, compress):
Georg Brandlb84c1372007-01-21 10:28:43 +00001426 class Subclass(cls):
1427 def __init__(self, newarg=None, *args):
1428 cls.__init__(self, *args)
1429 try:
1430 Subclass(newarg=1)
1431 except TypeError, err:
1432 # we expect type errors because of wrong argument count
Ezio Melottiaa980582010-01-23 23:04:36 +00001433 self.assertNotIn("does not take keyword arguments", err.args[0])
Georg Brandlb84c1372007-01-21 10:28:43 +00001434
1435
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001436libreftest = """ Doctest for examples in the library reference: libitertools.tex
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001437
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001438
1439>>> amounts = [120.15, 764.05, 823.14]
1440>>> for checknum, amount in izip(count(1200), amounts):
1441... print 'Check %d is for $%.2f' % (checknum, amount)
1442...
1443Check 1200 is for $120.15
1444Check 1201 is for $764.05
1445Check 1202 is for $823.14
1446
1447>>> import operator
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001448>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
1449... print cube
1450...
14511
14528
145327
1454
1455>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
Raymond Hettinger3567a872003-06-28 05:44:36 +00001456>>> for name in islice(reportlines, 3, None, 2):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001457... print name.title()
1458...
1459Alex
1460Laura
1461Martin
1462Walter
1463Samuele
1464
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001465>>> from operator import itemgetter
1466>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Armin Rigoa3f09272006-05-28 19:13:17 +00001467>>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001468>>> for k, g in groupby(di, itemgetter(1)):
1469... print k, map(itemgetter(0), g)
1470...
14711 ['a', 'c', 'e']
14722 ['b', 'd', 'f']
14733 ['g']
1474
Raymond Hettinger734fb572004-01-20 20:04:40 +00001475# Find runs of consecutive numbers using groupby. The key to the solution
1476# is differencing with a range so that consecutive numbers all appear in
1477# same group.
1478>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
Ezio Melottidde5b942010-02-03 05:37:26 +00001479>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Raymond Hettinger734fb572004-01-20 20:04:40 +00001480... print map(operator.itemgetter(1), g)
1481...
1482[1]
1483[4, 5, 6]
1484[10]
1485[15, 16, 17, 18]
1486[22]
1487[25, 26, 27, 28]
1488
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001489>>> def take(n, iterable):
1490... "Return first n items of the iterable as a list"
1491... return list(islice(iterable, n))
Raymond Hettingera098b332003-09-08 23:58:40 +00001492
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001493>>> def enumerate(iterable, start=0):
1494... return izip(count(start), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001495
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001496>>> def tabulate(function, start=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001497... "Return function(0), function(1), ..."
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001498... return imap(function, count(start))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001499
Raymond Hettingerf9bce832009-02-19 05:34:35 +00001500>>> def nth(iterable, n, default=None):
1501... "Returns the nth item or a default value"
1502... return next(islice(iterable, n, None), default)
Raymond Hettinger60eca932003-02-09 06:40:58 +00001503
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001504>>> def quantify(iterable, pred=bool):
1505... "Count how many times the predicate is true"
1506... return sum(imap(pred, iterable))
Raymond Hettinger60eca932003-02-09 06:40:58 +00001507
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001508>>> def padnone(iterable):
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001509... "Returns the sequence elements and then returns None indefinitely"
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001510... return chain(iterable, repeat(None))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001511
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001512>>> def ncycles(iterable, n):
Ezio Melottic2077b02011-03-16 12:34:31 +02001513... "Returns the sequence elements n times"
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001514... return chain(*repeat(iterable, n))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001515
1516>>> def dotproduct(vec1, vec2):
1517... return sum(imap(operator.mul, vec1, vec2))
1518
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001519>>> def flatten(listOfLists):
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001520... return list(chain.from_iterable(listOfLists))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001521
1522>>> def repeatfunc(func, times=None, *args):
1523... "Repeat calls to func with specified arguments."
1524... " Example: repeatfunc(random.random)"
1525... if times is None:
1526... return starmap(func, repeat(args))
1527... else:
1528... return starmap(func, repeat(args, times))
1529
Raymond Hettingerd591f662003-10-26 15:34:50 +00001530>>> def pairwise(iterable):
1531... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1532... a, b = tee(iterable)
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001533... for elem in b:
1534... break
Raymond Hettingerad983e72003-11-12 14:32:26 +00001535... return izip(a, b)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001536
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001537>>> def grouper(n, iterable, fillvalue=None):
Raymond Hettingerefdf7062008-07-30 07:27:30 +00001538... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001539... args = [iter(iterable)] * n
Raymond Hettingerf080e6d2008-07-31 01:19:50 +00001540... return izip_longest(fillvalue=fillvalue, *args)
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001541
1542>>> def roundrobin(*iterables):
Raymond Hettingerefdf7062008-07-30 07:27:30 +00001543... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001544... # Recipe credited to George Sakkis
1545... pending = len(iterables)
1546... nexts = cycle(iter(it).next for it in iterables)
1547... while pending:
1548... try:
1549... for next in nexts:
1550... yield next()
1551... except StopIteration:
1552... pending -= 1
1553... nexts = cycle(islice(nexts, pending))
1554
1555>>> def powerset(iterable):
Raymond Hettinger68d919e2009-01-25 21:31:47 +00001556... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
1557... s = list(iterable)
1558... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001559
Raymond Hettinger44e15812009-01-02 21:26:45 +00001560>>> def unique_everseen(iterable, key=None):
1561... "List unique elements, preserving order. Remember all elements ever seen."
1562... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
1563... # unique_everseen('ABBCcAD', str.lower) --> A B C D
1564... seen = set()
1565... seen_add = seen.add
1566... if key is None:
1567... for element in iterable:
1568... if element not in seen:
1569... seen_add(element)
1570... yield element
1571... else:
1572... for element in iterable:
1573... k = key(element)
1574... if k not in seen:
1575... seen_add(k)
1576... yield element
1577
1578>>> def unique_justseen(iterable, key=None):
1579... "List unique elements, preserving order. Remember only the element just seen."
1580... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
1581... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
1582... return imap(next, imap(itemgetter(1), groupby(iterable, key)))
1583
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001584This is not part of the examples but it tests to make sure the definitions
1585perform as purported.
1586
Raymond Hettingera098b332003-09-08 23:58:40 +00001587>>> take(10, count())
1588[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1589
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001590>>> list(enumerate('abc'))
1591[(0, 'a'), (1, 'b'), (2, 'c')]
1592
1593>>> list(islice(tabulate(lambda x: 2*x), 4))
1594[0, 2, 4, 6]
1595
1596>>> nth('abcde', 3)
Raymond Hettingerd507afd2009-02-04 10:52:32 +00001597'd'
1598
1599>>> nth('abcde', 9) is None
1600True
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001601
Raymond Hettingerdbe3d282003-10-05 16:47:36 +00001602>>> quantify(xrange(99), lambda x: x%2==0)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000160350
1604
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001605>>> a = [[1, 2, 3], [4, 5, 6]]
1606>>> flatten(a)
1607[1, 2, 3, 4, 5, 6]
1608
1609>>> list(repeatfunc(pow, 5, 2, 3))
1610[8, 8, 8, 8, 8]
1611
1612>>> import random
1613>>> take(5, imap(int, repeatfunc(random.random)))
1614[0, 0, 0, 0, 0]
1615
Raymond Hettingerd591f662003-10-26 15:34:50 +00001616>>> list(pairwise('abcd'))
1617[('a', 'b'), ('b', 'c'), ('c', 'd')]
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001618
Raymond Hettingerd591f662003-10-26 15:34:50 +00001619>>> list(pairwise([]))
1620[]
1621
1622>>> list(pairwise('a'))
Raymond Hettingerbefa37d2003-06-18 19:25:37 +00001623[]
1624
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001625>>> list(islice(padnone('abc'), 0, 6))
1626['a', 'b', 'c', None, None, None]
1627
1628>>> list(ncycles('abc', 3))
1629['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
1630
1631>>> dotproduct([1,2,3], [4,5,6])
163232
1633
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001634>>> list(grouper(3, 'abcdefg', 'x'))
1635[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
1636
1637>>> list(roundrobin('abc', 'd', 'ef'))
1638['a', 'd', 'e', 'b', 'f', 'c']
1639
Raymond Hettinger68d919e2009-01-25 21:31:47 +00001640>>> list(powerset([1,2,3]))
1641[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001642
Raymond Hettinger560f9a82009-01-27 13:26:35 +00001643>>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
1644True
1645
1646>>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
1647True
1648
Raymond Hettinger44e15812009-01-02 21:26:45 +00001649>>> list(unique_everseen('AAAABBBCCDAABBB'))
1650['A', 'B', 'C', 'D']
1651
1652>>> list(unique_everseen('ABBCcAD', str.lower))
1653['A', 'B', 'C', 'D']
1654
1655>>> list(unique_justseen('AAAABBBCCDAABBB'))
1656['A', 'B', 'C', 'D', 'A', 'B']
1657
1658>>> list(unique_justseen('ABBCcAD', str.lower))
1659['A', 'B', 'C', 'A', 'D']
1660
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001661"""
1662
1663__test__ = {'libreftest' : libreftest}
1664
1665def test_main(verbose=None):
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001666 test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
Georg Brandlb84c1372007-01-21 10:28:43 +00001667 RegressionTests, LengthTransparency,
Serhiy Storchaka6c467a42013-04-06 22:51:29 +03001668 SubclassWithKwargsTest, TestExamples)
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001669 test_support.run_unittest(*test_classes)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001670
1671 # verify reference counting
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001672 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger02420702003-06-29 20:36:23 +00001673 import gc
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001674 counts = [None] * 5
1675 for i in xrange(len(counts)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001676 test_support.run_unittest(*test_classes)
Raymond Hettinger02420702003-06-29 20:36:23 +00001677 gc.collect()
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001678 counts[i] = sys.gettotalrefcount()
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001679 print counts
1680
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001681 # doctest the examples in the library reference
Raymond Hettinger929f06c2003-05-16 23:16:36 +00001682 test_support.run_doctest(sys.modules[__name__], verbose)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001683
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001684if __name__ == "__main__":
1685 test_main(verbose=True)