blob: 511094e55498d9ba9ae7dd38a31b9d3667e13874 [file] [log] [blame]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Raymond Hettinger96ef8112003-02-01 00:10:11 +00003from itertools import *
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02004import weakref
Raymond Hettinger8a882a72009-02-12 12:08:18 +00005from decimal import Decimal
Raymond Hettingerde09acf2009-02-12 12:53:53 +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 Hettingera3e1ad22009-11-30 22:02:31 +000010import copy
11import pickle
Christian Heimesc3f30c42008-02-22 16:37:40 +000012from functools import reduce
Serhiy Storchaka2dae92a2013-12-09 17:45:57 +020013import sys
14import struct
Benjamin Petersonee8712c2008-05-20 21:35:26 +000015maxsize = support.MAX_Py_ssize_t
Guido van Rossum360e4b82007-05-14 22:51:27 +000016minsize = -maxsize-1
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000017
Guido van Rossum801f0d72006-08-24 19:48:10 +000018def lzip(*args):
19 return list(zip(*args))
20
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000021def onearg(x):
22 'Test function of one argument'
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000023 return 2*x
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000024
25def errfunc(*args):
26 'Test function that raises an error'
27 raise ValueError
28
29def gen3():
30 'Non-restartable source sequence'
31 for i in (0, 1, 2):
32 yield i
33
34def isEven(x):
35 'Test predicate'
36 return x%2==0
37
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000038def isOdd(x):
39 'Test predicate'
40 return x%2==1
41
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000042def tupleize(*args):
43 return args
44
45def irange(n):
46 for i in range(n):
47 yield i
48
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000049class StopNow:
50 'Class emulating an empty iterable.'
51 def __iter__(self):
52 return self
Georg Brandla18af4e2007-04-21 15:47:16 +000053 def __next__(self):
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000054 raise StopIteration
Raymond Hettinger96ef8112003-02-01 00:10:11 +000055
Raymond Hettinger02420702003-06-29 20:36:23 +000056def take(n, seq):
57 'Convenience function for partially consuming a long of infinite iterable'
58 return list(islice(seq, n))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000059
Christian Heimes78644762008-03-04 23:39:23 +000060def prod(iterable):
61 return reduce(operator.mul, iterable, 1)
62
Christian Heimes380f7f22008-02-28 11:19:05 +000063def fact(n):
64 'Factorial'
Christian Heimes78644762008-03-04 23:39:23 +000065 return prod(range(1, n+1))
66
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000067# root level methods for pickling ability
68def testR(r):
69 return r[0]
70
71def testR2(r):
72 return r[2]
73
74def underten(x):
75 return x<10
76
Serhiy Storchakabad12572014-12-15 14:03:42 +020077picklecopiers = [lambda s, proto=proto: pickle.loads(pickle.dumps(s, proto))
78 for proto in range(pickle.HIGHEST_PROTOCOL + 1)]
79
Raymond Hettinger96ef8112003-02-01 00:10:11 +000080class TestBasicOps(unittest.TestCase):
Raymond Hettinger482ba772010-12-01 22:48:00 +000081
Serhiy Storchakabad12572014-12-15 14:03:42 +020082 def pickletest(self, protocol, it, stop=4, take=1, compare=None):
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000083 """Test that an iterator is the same after pickling, also when part-consumed"""
84 def expand(it, i=0):
85 # Recursively expand iterables, within sensible bounds
86 if i > 10:
87 raise RuntimeError("infinite recursion encountered")
88 if isinstance(it, str):
89 return it
90 try:
91 l = list(islice(it, stop))
92 except TypeError:
93 return it # can't expand it
94 return [expand(e, i+1) for e in l]
95
96 # Test the initial copy against the original
Serhiy Storchakabad12572014-12-15 14:03:42 +020097 dump = pickle.dumps(it, protocol)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000098 i2 = pickle.loads(dump)
99 self.assertEqual(type(it), type(i2))
100 a, b = expand(it), expand(i2)
101 self.assertEqual(a, b)
102 if compare:
103 c = expand(compare)
104 self.assertEqual(a, c)
105
106 # Take from the copy, and create another copy and compare them.
107 i3 = pickle.loads(dump)
108 took = 0
109 try:
110 for i in range(take):
111 next(i3)
112 took += 1
113 except StopIteration:
114 pass #in case there is less data than 'take'
Serhiy Storchakabad12572014-12-15 14:03:42 +0200115 dump = pickle.dumps(i3, protocol)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000116 i4 = pickle.loads(dump)
117 a, b = expand(i3), expand(i4)
118 self.assertEqual(a, b)
119 if compare:
120 c = expand(compare[took:])
121 self.assertEqual(a, c);
122
Raymond Hettinger482ba772010-12-01 22:48:00 +0000123 def test_accumulate(self):
124 self.assertEqual(list(accumulate(range(10))), # one positional arg
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000125 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
126 self.assertEqual(list(accumulate(iterable=range(10))), # kw arg
127 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
Raymond Hettinger482ba772010-12-01 22:48:00 +0000128 for typ in int, complex, Decimal, Fraction: # multiple types
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000129 self.assertEqual(
130 list(accumulate(map(typ, range(10)))),
Raymond Hettinger482ba772010-12-01 22:48:00 +0000131 list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])))
Raymond Hettinger2d93e6e2010-12-03 02:33:53 +0000132 self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc']) # works with non-numeric
Raymond Hettinger482ba772010-12-01 22:48:00 +0000133 self.assertEqual(list(accumulate([])), []) # empty iterable
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000134 self.assertEqual(list(accumulate([7])), [7]) # iterable of length one
Raymond Hettinger5d446132011-03-27 18:52:10 -0700135 self.assertRaises(TypeError, accumulate, range(10), 5, 6) # too many args
Raymond Hettinger482ba772010-12-01 22:48:00 +0000136 self.assertRaises(TypeError, accumulate) # too few args
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000137 self.assertRaises(TypeError, accumulate, x=range(10)) # unexpected kwd arg
Raymond Hettinger482ba772010-12-01 22:48:00 +0000138 self.assertRaises(TypeError, list, accumulate([1, []])) # args that don't add
139
Raymond Hettinger5d446132011-03-27 18:52:10 -0700140 s = [2, 8, 9, 5, 7, 0, 3, 4, 1, 6]
141 self.assertEqual(list(accumulate(s, min)),
142 [2, 2, 2, 2, 2, 0, 0, 0, 0, 0])
143 self.assertEqual(list(accumulate(s, max)),
144 [2, 8, 9, 9, 9, 9, 9, 9, 9, 9])
145 self.assertEqual(list(accumulate(s, operator.mul)),
146 [2, 16, 144, 720, 5040, 0, 0, 0, 0, 0])
147 with self.assertRaises(TypeError):
148 list(accumulate(s, chr)) # unary-operation
Serhiy Storchakabad12572014-12-15 14:03:42 +0200149 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
150 self.pickletest(proto, accumulate(range(10))) # test pickling
Raymond Hettinger5d446132011-03-27 18:52:10 -0700151
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000152 def test_chain(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000153
154 def chain2(*iterables):
155 'Pure python version in the docs'
156 for it in iterables:
157 for element in it:
158 yield element
159
160 for c in (chain, chain2):
161 self.assertEqual(list(c('abc', 'def')), list('abcdef'))
162 self.assertEqual(list(c('abc')), list('abc'))
163 self.assertEqual(list(c('')), [])
164 self.assertEqual(take(4, c('abc', 'def')), list('abcd'))
165 self.assertRaises(TypeError, list,c(2, 3))
Christian Heimesf16baeb2008-02-29 14:57:44 +0000166
167 def test_chain_from_iterable(self):
168 self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef'))
169 self.assertEqual(list(chain.from_iterable(['abc'])), list('abc'))
170 self.assertEqual(list(chain.from_iterable([''])), [])
171 self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd'))
172 self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000173
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000174 def test_chain_reducible(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200175 for oper in [copy.deepcopy] + picklecopiers:
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000176 it = chain('abc', 'def')
177 self.assertEqual(list(oper(it)), list('abcdef'))
178 self.assertEqual(next(it), 'a')
179 self.assertEqual(list(oper(it)), list('bcdef'))
180
181 self.assertEqual(list(oper(chain(''))), [])
182 self.assertEqual(take(4, oper(chain('abc', 'def'))), list('abcd'))
183 self.assertRaises(TypeError, list, oper(chain(2, 3)))
Serhiy Storchakabad12572014-12-15 14:03:42 +0200184 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
185 self.pickletest(proto, chain('abc', 'def'), compare=list('abcdef'))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000186
Christian Heimes380f7f22008-02-28 11:19:05 +0000187 def test_combinations(self):
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000188 self.assertRaises(TypeError, combinations, 'abc') # missing r argument
Christian Heimes380f7f22008-02-28 11:19:05 +0000189 self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
Christian Heimes78644762008-03-04 23:39:23 +0000190 self.assertRaises(TypeError, combinations, None) # pool is not iterable
Christian Heimes380f7f22008-02-28 11:19:05 +0000191 self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000192
Serhiy Storchakabad12572014-12-15 14:03:42 +0200193 for op in [lambda a:a] + picklecopiers:
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000194 self.assertEqual(list(op(combinations('abc', 32))), []) # r > n
195
196 self.assertEqual(list(op(combinations('ABCD', 2))),
197 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
198 testIntermediate = combinations('ABCD', 2)
199 next(testIntermediate)
200 self.assertEqual(list(op(testIntermediate)),
201 [('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
202
203 self.assertEqual(list(op(combinations(range(4), 3))),
204 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
205 testIntermediate = combinations(range(4), 3)
206 next(testIntermediate)
207 self.assertEqual(list(op(testIntermediate)),
208 [(0,1,3), (0,2,3), (1,2,3)])
209
Christian Heimes78644762008-03-04 23:39:23 +0000210
211 def combinations1(iterable, r):
212 'Pure python version shown in the docs'
213 pool = tuple(iterable)
214 n = len(pool)
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000215 if r > n:
216 return
Christian Heimes78644762008-03-04 23:39:23 +0000217 indices = list(range(r))
218 yield tuple(pool[i] for i in indices)
219 while 1:
220 for i in reversed(range(r)):
221 if indices[i] != i + n - r:
222 break
223 else:
224 return
225 indices[i] += 1
226 for j in range(i+1, r):
227 indices[j] = indices[j-1] + 1
228 yield tuple(pool[i] for i in indices)
229
230 def combinations2(iterable, r):
231 'Pure python version shown in the docs'
232 pool = tuple(iterable)
233 n = len(pool)
234 for indices in permutations(range(n), r):
235 if sorted(indices) == list(indices):
236 yield tuple(pool[i] for i in indices)
237
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000238 def combinations3(iterable, r):
239 'Pure python version from cwr()'
240 pool = tuple(iterable)
241 n = len(pool)
242 for indices in combinations_with_replacement(range(n), r):
243 if len(set(indices)) == r:
244 yield tuple(pool[i] for i in indices)
245
Christian Heimes78644762008-03-04 23:39:23 +0000246 for n in range(7):
Christian Heimes380f7f22008-02-28 11:19:05 +0000247 values = [5*x-12 for x in range(n)]
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000248 for r in range(n+2):
Christian Heimes380f7f22008-02-28 11:19:05 +0000249 result = list(combinations(values, r))
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000250 self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs
Christian Heimes380f7f22008-02-28 11:19:05 +0000251 self.assertEqual(len(result), len(set(result))) # no repeats
252 self.assertEqual(result, sorted(result)) # lexicographic order
253 for c in result:
254 self.assertEqual(len(c), r) # r-length combinations
255 self.assertEqual(len(set(c)), r) # no duplicate elements
256 self.assertEqual(list(c), sorted(c)) # keep original ordering
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000257 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000258 self.assertEqual(list(c),
259 [e for e in values if e in c]) # comb is a subsequence of the input iterable
Christian Heimes78644762008-03-04 23:39:23 +0000260 self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000261 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000262 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
Christian Heimes78644762008-03-04 23:39:23 +0000263
Serhiy Storchakabad12572014-12-15 14:03:42 +0200264 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
265 self.pickletest(proto, combinations(values, r)) # test pickling
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000266
267 # Test implementation detail: tuple re-use
Alex Gaynore151d212011-07-17 16:21:30 -0700268 @support.impl_detail("tuple reuse is specific to CPython")
269 def test_combinations_tuple_reuse(self):
Christian Heimes78644762008-03-04 23:39:23 +0000270 self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
271 self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
272
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000273 def test_combinations_with_replacement(self):
274 cwr = combinations_with_replacement
275 self.assertRaises(TypeError, cwr, 'abc') # missing r argument
276 self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments
277 self.assertRaises(TypeError, cwr, None) # pool is not iterable
278 self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000279
Serhiy Storchakabad12572014-12-15 14:03:42 +0200280 for op in [lambda a:a] + picklecopiers:
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000281 self.assertEqual(list(op(cwr('ABC', 2))),
282 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
283 testIntermediate = cwr('ABC', 2)
284 next(testIntermediate)
285 self.assertEqual(list(op(testIntermediate)),
286 [('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
287
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000288
289 def cwr1(iterable, r):
290 'Pure python version shown in the docs'
291 # number items returned: (n+r-1)! / r! / (n-1)! when n>0
292 pool = tuple(iterable)
293 n = len(pool)
294 if not n and r:
295 return
296 indices = [0] * r
297 yield tuple(pool[i] for i in indices)
298 while 1:
299 for i in reversed(range(r)):
300 if indices[i] != n - 1:
301 break
302 else:
303 return
304 indices[i:] = [indices[i] + 1] * (r - i)
305 yield tuple(pool[i] for i in indices)
306
307 def cwr2(iterable, r):
308 'Pure python version shown in the docs'
309 pool = tuple(iterable)
310 n = len(pool)
311 for indices in product(range(n), repeat=r):
312 if sorted(indices) == list(indices):
313 yield tuple(pool[i] for i in indices)
314
315 def numcombs(n, r):
316 if not n:
317 return 0 if r else 1
318 return fact(n+r-1) / fact(r)/ fact(n-1)
319
320 for n in range(7):
321 values = [5*x-12 for x in range(n)]
322 for r in range(n+2):
323 result = list(cwr(values, r))
324
325 self.assertEqual(len(result), numcombs(n, r)) # right number of combs
326 self.assertEqual(len(result), len(set(result))) # no repeats
327 self.assertEqual(result, sorted(result)) # lexicographic order
328
329 regular_combs = list(combinations(values, r)) # compare to combs without replacement
330 if n == 0 or r <= 1:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000331 self.assertEqual(result, regular_combs) # cases that should be identical
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000332 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000333 self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000334
335 for c in result:
336 self.assertEqual(len(c), r) # r-length combinations
337 noruns = [k for k,v in groupby(c)] # combo without consecutive repeats
338 self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive
339 self.assertEqual(list(c), sorted(c)) # keep original ordering
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000340 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000341 self.assertEqual(noruns,
342 [e for e in values if e in c]) # comb is a subsequence of the input iterable
343 self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version
344 self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version
345
Serhiy Storchakabad12572014-12-15 14:03:42 +0200346 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
347 self.pickletest(proto, cwr(values,r)) # test pickling
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000348
349 # Test implementation detail: tuple re-use
350
Alex Gaynore151d212011-07-17 16:21:30 -0700351 @support.impl_detail("tuple reuse is specific to CPython")
352 def test_combinations_with_replacement_tuple_reuse(self):
353 cwr = combinations_with_replacement
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000354 self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
355 self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
356
Christian Heimes78644762008-03-04 23:39:23 +0000357 def test_permutations(self):
358 self.assertRaises(TypeError, permutations) # too few arguments
359 self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000360 self.assertRaises(TypeError, permutations, None) # pool is not iterable
361 self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000362 self.assertEqual(list(permutations('abc', 32)), []) # r > n
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000363 self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
Christian Heimes78644762008-03-04 23:39:23 +0000364 self.assertEqual(list(permutations(range(3), 2)),
365 [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
366
367 def permutations1(iterable, r=None):
368 'Pure python version shown in the docs'
369 pool = tuple(iterable)
370 n = len(pool)
371 r = n if r is None else r
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000372 if r > n:
373 return
Christian Heimes78644762008-03-04 23:39:23 +0000374 indices = list(range(n))
375 cycles = list(range(n-r+1, n+1))[::-1]
376 yield tuple(pool[i] for i in indices[:r])
377 while n:
378 for i in reversed(range(r)):
379 cycles[i] -= 1
380 if cycles[i] == 0:
381 indices[i:] = indices[i+1:] + indices[i:i+1]
382 cycles[i] = n - i
383 else:
384 j = cycles[i]
385 indices[i], indices[-j] = indices[-j], indices[i]
386 yield tuple(pool[i] for i in indices[:r])
387 break
388 else:
389 return
390
391 def permutations2(iterable, r=None):
392 'Pure python version shown in the docs'
393 pool = tuple(iterable)
394 n = len(pool)
395 r = n if r is None else r
396 for indices in product(range(n), repeat=r):
397 if len(set(indices)) == r:
398 yield tuple(pool[i] for i in indices)
399
400 for n in range(7):
401 values = [5*x-12 for x in range(n)]
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000402 for r in range(n+2):
Christian Heimes78644762008-03-04 23:39:23 +0000403 result = list(permutations(values, r))
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000404 self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms
Christian Heimes78644762008-03-04 23:39:23 +0000405 self.assertEqual(len(result), len(set(result))) # no repeats
406 self.assertEqual(result, sorted(result)) # lexicographic order
407 for p in result:
408 self.assertEqual(len(p), r) # r-length permutations
409 self.assertEqual(len(set(p)), r) # no duplicate elements
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000410 self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
Christian Heimes78644762008-03-04 23:39:23 +0000411 self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000412 self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
Christian Heimes78644762008-03-04 23:39:23 +0000413 if r == n:
414 self.assertEqual(result, list(permutations(values, None))) # test r as None
415 self.assertEqual(result, list(permutations(values))) # test default r
416
Serhiy Storchakabad12572014-12-15 14:03:42 +0200417 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
418 self.pickletest(proto, permutations(values, r)) # test pickling
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000419
Zachary Waredca807b2014-04-24 13:22:05 -0500420 @support.impl_detail("tuple reuse is specific to CPython")
Alex Gaynore151d212011-07-17 16:21:30 -0700421 def test_permutations_tuple_reuse(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000422 self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
Christian Heimes78644762008-03-04 23:39:23 +0000423 self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
Christian Heimes380f7f22008-02-28 11:19:05 +0000424
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000425 def test_combinatorics(self):
426 # Test relationships between product(), permutations(),
427 # combinations() and combinations_with_replacement().
428
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000429 for n in range(6):
430 s = 'ABCDEFG'[:n]
431 for r in range(8):
432 prod = list(product(s, repeat=r))
433 cwr = list(combinations_with_replacement(s, r))
434 perm = list(permutations(s, r))
435 comb = list(combinations(s, r))
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000436
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000437 # Check size
Ezio Melottib3aedd42010-11-20 19:04:17 +0000438 self.assertEqual(len(prod), n**r)
439 self.assertEqual(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
440 self.assertEqual(len(perm), 0 if r>n else fact(n) / fact(n-r))
441 self.assertEqual(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000442
443 # Check lexicographic order without repeated tuples
Ezio Melottib3aedd42010-11-20 19:04:17 +0000444 self.assertEqual(prod, sorted(set(prod)))
445 self.assertEqual(cwr, sorted(set(cwr)))
446 self.assertEqual(perm, sorted(set(perm)))
447 self.assertEqual(comb, sorted(set(comb)))
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000448
449 # Check interrelationships
Ezio Melottib3aedd42010-11-20 19:04:17 +0000450 self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
451 self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups
Raymond Hettingerda6bc522009-01-27 10:39:42 +0000452 self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted
453 self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups
454 self.assertEqual(comb, list(filter(set(cwr).__contains__, perm))) # comb: perm that is a cwr
455 self.assertEqual(comb, list(filter(set(perm).__contains__, cwr))) # comb: cwr that is a perm
456 self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm
Raymond Hettingereb508ad2009-01-27 09:35:21 +0000457
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +0000458 def test_compress(self):
Raymond Hettinger15a49502009-02-19 02:17:09 +0000459 self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +0000460 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
461 self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list(''))
462 self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF'))
463 self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC'))
464 self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC'))
465 n = 10000
466 data = chain.from_iterable(repeat(range(6), n))
467 selectors = chain.from_iterable(repeat((0, 1)))
468 self.assertEqual(list(compress(data, selectors)), [1,3,5] * n)
469 self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable
470 self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable
471 self.assertRaises(TypeError, compress, range(6)) # too few args
472 self.assertRaises(TypeError, compress, range(6), None) # too many args
473
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000474 # check copy, deepcopy, pickle
Serhiy Storchakabad12572014-12-15 14:03:42 +0200475 for op in [lambda a:copy.copy(a), lambda a:copy.deepcopy(a)] + picklecopiers:
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000476 for data, selectors, result1, result2 in [
477 ('ABCDEF', [1,0,1,0,1,1], 'ACEF', 'CEF'),
478 ('ABCDEF', [0,0,0,0,0,0], '', ''),
479 ('ABCDEF', [1,1,1,1,1,1], 'ABCDEF', 'BCDEF'),
480 ('ABCDEF', [1,0,1], 'AC', 'C'),
481 ('ABC', [0,1,1,1,1,1], 'BC', 'C'),
482 ]:
483
484 self.assertEqual(list(op(compress(data=data, selectors=selectors))), list(result1))
485 self.assertEqual(list(op(compress(data, selectors))), list(result1))
486 testIntermediate = compress(data, selectors)
487 if result1:
488 next(testIntermediate)
489 self.assertEqual(list(op(testIntermediate)), list(result2))
490
491
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000492 def test_count(self):
Guido van Rossum801f0d72006-08-24 19:48:10 +0000493 self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
494 self.assertEqual(lzip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
495 self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)])
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000496 self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
497 self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
Raymond Hettinger30729212009-02-12 06:28:27 +0000498 self.assertRaises(TypeError, count, 2, 3, 4)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000499 self.assertRaises(TypeError, count, 'a')
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000500 self.assertEqual(list(islice(count(maxsize-5), 10)),
501 list(range(maxsize-5, maxsize+5)))
502 self.assertEqual(list(islice(count(-maxsize-5), 10)),
503 list(range(-maxsize-5, -maxsize+5)))
Kristjan Valur Jonsson35722a92011-03-30 11:04:28 +0000504 self.assertEqual(list(islice(count(10, maxsize+5), 3)),
505 list(range(10, 10+3*(maxsize+5), maxsize+5)))
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000506 c = count(3)
507 self.assertEqual(repr(c), 'count(3)')
Georg Brandla18af4e2007-04-21 15:47:16 +0000508 next(c)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000509 self.assertEqual(repr(c), 'count(4)')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000510 c = count(-9)
511 self.assertEqual(repr(c), 'count(-9)')
Georg Brandla18af4e2007-04-21 15:47:16 +0000512 next(c)
Raymond Hettinger30729212009-02-12 06:28:27 +0000513 self.assertEqual(repr(count(10.25)), 'count(10.25)')
Georg Brandla18af4e2007-04-21 15:47:16 +0000514 self.assertEqual(next(c), -8)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000515 for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300516 # Test repr
517 r1 = repr(count(i))
518 r2 = 'count(%r)'.__mod__(i)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000519 self.assertEqual(r1, r2)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000520
Raymond Hettingera3e1ad22009-11-30 22:02:31 +0000521 # check copy, deepcopy, pickle
522 for value in -3, 3, maxsize-5, maxsize+5:
523 c = count(value)
524 self.assertEqual(next(copy.copy(c)), value)
525 self.assertEqual(next(copy.deepcopy(c)), value)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200526 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
527 self.pickletest(proto, count(value))
Raymond Hettingera3e1ad22009-11-30 22:02:31 +0000528
Kristjan Valur Jonsson35722a92011-03-30 11:04:28 +0000529 #check proper internal error handling for large "step' sizes
530 count(1, maxsize+5); sys.exc_info()
531
Raymond Hettinger30729212009-02-12 06:28:27 +0000532 def test_count_with_stride(self):
533 self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingereb13fdd2009-02-21 22:30:12 +0000534 self.assertEqual(lzip('abc',count(start=2,step=3)),
535 [('a', 2), ('b', 5), ('c', 8)])
536 self.assertEqual(lzip('abc',count(step=-1)),
537 [('a', 0), ('b', -1), ('c', -2)])
Raymond Hettinger30729212009-02-12 06:28:27 +0000538 self.assertEqual(lzip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
539 self.assertEqual(lzip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
Raymond Hettinger9e8dbbc2009-02-14 04:21:49 +0000540 self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettinger30729212009-02-12 06:28:27 +0000541 self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
542 self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
543 self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
Raymond Hettinger8a882a72009-02-12 12:08:18 +0000544 self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
545 [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
Raymond Hettingerde09acf2009-02-12 12:53:53 +0000546 self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
547 [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
Raymond Hettinger30729212009-02-12 06:28:27 +0000548 self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
549 c = count(3, 5)
550 self.assertEqual(repr(c), 'count(3, 5)')
551 next(c)
552 self.assertEqual(repr(c), 'count(8, 5)')
553 c = count(-9, 0)
554 self.assertEqual(repr(c), 'count(-9, 0)')
555 next(c)
556 self.assertEqual(repr(c), 'count(-9, 0)')
557 c = count(-9, -3)
558 self.assertEqual(repr(c), 'count(-9, -3)')
559 next(c)
560 self.assertEqual(repr(c), 'count(-12, -3)')
561 self.assertEqual(repr(c), 'count(-12, -3)')
562 self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
563 self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int
564 self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0
565 for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
566 for j in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 1, 10, sys.maxsize-5, sys.maxsize+5):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300567 # Test repr
568 r1 = repr(count(i, j))
Raymond Hettinger30729212009-02-12 06:28:27 +0000569 if j == 1:
Serhiy Storchaka95949422013-08-27 19:40:23 +0300570 r2 = ('count(%r)' % i)
Raymond Hettinger30729212009-02-12 06:28:27 +0000571 else:
Serhiy Storchaka95949422013-08-27 19:40:23 +0300572 r2 = ('count(%r, %r)' % (i, j))
Raymond Hettinger30729212009-02-12 06:28:27 +0000573 self.assertEqual(r1, r2)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200574 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
575 self.pickletest(proto, count(i, j))
Raymond Hettinger30729212009-02-12 06:28:27 +0000576
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000577 def test_cycle(self):
Raymond Hettinger02420702003-06-29 20:36:23 +0000578 self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000579 self.assertEqual(list(cycle('')), [])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000580 self.assertRaises(TypeError, cycle)
581 self.assertRaises(TypeError, cycle, 5)
582 self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000583
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000584 # check copy, deepcopy, pickle
585 c = cycle('abc')
586 self.assertEqual(next(c), 'a')
587 #simple copy currently not supported, because __reduce__ returns
588 #an internal iterator
589 #self.assertEqual(take(10, copy.copy(c)), list('bcabcabcab'))
590 self.assertEqual(take(10, copy.deepcopy(c)), list('bcabcabcab'))
Serhiy Storchakabad12572014-12-15 14:03:42 +0200591 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
592 self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))),
593 list('bcabcabcab'))
594 next(c)
595 self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))),
596 list('cabcabcabc'))
597 next(c)
598 next(c)
599 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
600 self.pickletest(proto, cycle('abc'))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000601
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000602 def test_groupby(self):
603 # Check whether it accepts arguments correctly
604 self.assertEqual([], list(groupby([])))
605 self.assertEqual([], list(groupby([], key=id)))
606 self.assertRaises(TypeError, list, groupby('abc', []))
607 self.assertRaises(TypeError, groupby, None)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000608 self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000609
610 # Check normal input
611 s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
612 (2,15,22), (3,16,23), (3,17,23)]
613 dup = []
614 for k, g in groupby(s, lambda r:r[0]):
615 for elem in g:
616 self.assertEqual(k, elem[0])
617 dup.append(elem)
618 self.assertEqual(s, dup)
619
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000620 # Check normal pickled
Serhiy Storchakabad12572014-12-15 14:03:42 +0200621 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
622 dup = []
623 for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)):
624 for elem in g:
625 self.assertEqual(k, elem[0])
626 dup.append(elem)
627 self.assertEqual(s, dup)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000628
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000629 # Check nested case
630 dup = []
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000631 for k, g in groupby(s, testR):
632 for ik, ig in groupby(g, testR2):
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000633 for elem in ig:
634 self.assertEqual(k, elem[0])
635 self.assertEqual(ik, elem[2])
636 dup.append(elem)
637 self.assertEqual(s, dup)
638
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000639 # Check nested and pickled
Serhiy Storchakabad12572014-12-15 14:03:42 +0200640 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
641 dup = []
642 for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)):
643 for ik, ig in pickle.loads(pickle.dumps(groupby(g, testR2), proto)):
644 for elem in ig:
645 self.assertEqual(k, elem[0])
646 self.assertEqual(ik, elem[2])
647 dup.append(elem)
648 self.assertEqual(s, dup)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000649
650
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000651 # Check case where inner iterator is not used
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000652 keys = [k for k, g in groupby(s, testR)]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000653 expectedkeys = set([r[0] for r in s])
654 self.assertEqual(set(keys), expectedkeys)
655 self.assertEqual(len(keys), len(expectedkeys))
656
657 # Exercise pipes and filters style
658 s = 'abracadabra'
659 # sort s | uniq
Raymond Hettinger64958a12003-12-17 20:43:33 +0000660 r = [k for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000661 self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
662 # sort s | uniq -d
Raymond Hettinger64958a12003-12-17 20:43:33 +0000663 r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000664 self.assertEqual(r, ['a', 'b', 'r'])
665 # sort s | uniq -c
Raymond Hettinger64958a12003-12-17 20:43:33 +0000666 r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000667 self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
668 # sort s | uniq -c | sort -rn | head -3
Raymond Hettinger64958a12003-12-17 20:43:33 +0000669 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000670 self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
671
Georg Brandla18af4e2007-04-21 15:47:16 +0000672 # iter.__next__ failure
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000673 class ExpectedError(Exception):
674 pass
675 def delayed_raise(n=0):
676 for i in range(n):
677 yield 'yo'
678 raise ExpectedError
679 def gulp(iterable, keyp=None, func=list):
680 return [func(g) for k, g in groupby(iterable, keyp)]
681
Georg Brandla18af4e2007-04-21 15:47:16 +0000682 # iter.__next__ failure on outer object
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000683 self.assertRaises(ExpectedError, gulp, delayed_raise(0))
Georg Brandla18af4e2007-04-21 15:47:16 +0000684 # iter.__next__ failure on inner object
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000685 self.assertRaises(ExpectedError, gulp, delayed_raise(1))
686
687 # __cmp__ failure
688 class DummyCmp:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000689 def __eq__(self, dst):
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000690 raise ExpectedError
691 s = [DummyCmp(), DummyCmp(), None]
692
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000693 # __eq__ failure on outer object
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000694 self.assertRaises(ExpectedError, gulp, s, func=id)
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000695 # __eq__ failure on inner object
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000696 self.assertRaises(ExpectedError, gulp, s)
697
698 # keyfunc failure
699 def keyfunc(obj):
700 if keyfunc.skip > 0:
701 keyfunc.skip -= 1
702 return obj
703 else:
704 raise ExpectedError
705
706 # keyfunc failure on outer object
707 keyfunc.skip = 0
708 self.assertRaises(ExpectedError, gulp, [None], keyfunc)
709 keyfunc.skip = 1
710 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
711
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000712 def test_filter(self):
713 self.assertEqual(list(filter(isEven, range(6))), [0,2,4])
714 self.assertEqual(list(filter(None, [0,1,0,2,0])), [1,2])
715 self.assertEqual(list(filter(bool, [0,1,0,2,0])), [1,2])
716 self.assertEqual(take(4, filter(isEven, count())), [0,2,4,6])
717 self.assertRaises(TypeError, filter)
718 self.assertRaises(TypeError, filter, lambda x:x)
719 self.assertRaises(TypeError, filter, lambda x:x, range(6), 7)
720 self.assertRaises(TypeError, filter, isEven, 3)
721 self.assertRaises(TypeError, next, filter(range(6), range(6)))
Raymond Hettinger60eca932003-02-09 06:40:58 +0000722
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000723 # check copy, deepcopy, pickle
724 ans = [0,2,4]
725
726 c = filter(isEven, range(6))
727 self.assertEqual(list(copy.copy(c)), ans)
728 c = filter(isEven, range(6))
729 self.assertEqual(list(copy.deepcopy(c)), ans)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200730 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
731 c = filter(isEven, range(6))
732 self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans)
733 next(c)
734 self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans[1:])
735 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
736 c = filter(isEven, range(6))
737 self.pickletest(proto, c)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000738
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000739 def test_filterfalse(self):
740 self.assertEqual(list(filterfalse(isEven, range(6))), [1,3,5])
741 self.assertEqual(list(filterfalse(None, [0,1,0,2,0])), [0,0,0])
742 self.assertEqual(list(filterfalse(bool, [0,1,0,2,0])), [0,0,0])
743 self.assertEqual(take(4, filterfalse(isEven, count())), [1,3,5,7])
744 self.assertRaises(TypeError, filterfalse)
745 self.assertRaises(TypeError, filterfalse, lambda x:x)
746 self.assertRaises(TypeError, filterfalse, lambda x:x, range(6), 7)
747 self.assertRaises(TypeError, filterfalse, isEven, 3)
748 self.assertRaises(TypeError, next, filterfalse(range(6), range(6)))
Serhiy Storchakabad12572014-12-15 14:03:42 +0200749 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
750 self.pickletest(proto, filterfalse(isEven, range(6)))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000751
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000752 def test_zip(self):
753 # XXX This is rather silly now that builtin zip() calls zip()...
754 ans = [(x,y) for x, y in zip('abc',count())]
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000755 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000756 self.assertEqual(list(zip('abc', range(6))), lzip('abc', range(6)))
757 self.assertEqual(list(zip('abcdef', range(3))), lzip('abcdef', range(3)))
758 self.assertEqual(take(3,zip('abcdef', count())), lzip('abcdef', range(3)))
759 self.assertEqual(list(zip('abcdef')), lzip('abcdef'))
760 self.assertEqual(list(zip()), lzip())
761 self.assertRaises(TypeError, zip, 3)
762 self.assertRaises(TypeError, zip, range(3), 3)
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000763 self.assertEqual([tuple(list(pair)) for pair in zip('abc', 'def')],
Guido van Rossum801f0d72006-08-24 19:48:10 +0000764 lzip('abc', 'def'))
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000765 self.assertEqual([pair for pair in zip('abc', 'def')],
Guido van Rossum801f0d72006-08-24 19:48:10 +0000766 lzip('abc', 'def'))
Alex Gaynore151d212011-07-17 16:21:30 -0700767
768 @support.impl_detail("tuple reuse is specific to CPython")
769 def test_zip_tuple_reuse(self):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000770 ids = list(map(id, zip('abc', 'def')))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000771 self.assertEqual(min(ids), max(ids))
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000772 ids = list(map(id, list(zip('abc', 'def'))))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000773 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000774
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000775 # check copy, deepcopy, pickle
776 ans = [(x,y) for x, y in copy.copy(zip('abc',count()))]
777 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
778
779 ans = [(x,y) for x, y in copy.deepcopy(zip('abc',count()))]
780 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
781
Serhiy Storchakabad12572014-12-15 14:03:42 +0200782 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
783 ans = [(x,y) for x, y in pickle.loads(pickle.dumps(zip('abc',count()), proto))]
784 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000785
Serhiy Storchakabad12572014-12-15 14:03:42 +0200786 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
787 testIntermediate = zip('abc',count())
788 next(testIntermediate)
789 ans = [(x,y) for x, y in pickle.loads(pickle.dumps(testIntermediate, proto))]
790 self.assertEqual(ans, [('b', 1), ('c', 2)])
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000791
Serhiy Storchakabad12572014-12-15 14:03:42 +0200792 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
793 self.pickletest(proto, zip('abc', count()))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000794
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000795 def test_ziplongest(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000796 for args in [
797 ['abc', range(6)],
798 [range(6), 'abc'],
799 [range(1000), range(2000,2100), range(3000,3050)],
800 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
801 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
802 ]:
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000803 target = [tuple([arg[i] if i < len(arg) else None for arg in args])
804 for i in range(max(map(len, args)))]
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000805 self.assertEqual(list(zip_longest(*args)), target)
806 self.assertEqual(list(zip_longest(*args, **{})), target)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000807 target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000808 self.assertEqual(list(zip_longest(*args, **dict(fillvalue='X'))), target)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000809
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000810 self.assertEqual(take(3,zip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input
Thomas Wouterscf297e42007-02-23 15:07:44 +0000811
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000812 self.assertEqual(list(zip_longest()), list(zip()))
813 self.assertEqual(list(zip_longest([])), list(zip([])))
814 self.assertEqual(list(zip_longest('abcdef')), list(zip('abcdef')))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000816 self.assertEqual(list(zip_longest('abc', 'defg', **{})),
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000817 list(zip(list('abc')+[None], 'defg'))) # empty keyword dict
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000818 self.assertRaises(TypeError, zip_longest, 3)
819 self.assertRaises(TypeError, zip_longest, range(3), 3)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000820
821 for stmt in [
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000822 "zip_longest('abc', fv=1)",
823 "zip_longest('abc', fillvalue=1, bogus_keyword=None)",
Thomas Wouterscf297e42007-02-23 15:07:44 +0000824 ]:
825 try:
826 eval(stmt, globals(), locals())
827 except TypeError:
828 pass
829 else:
830 self.fail('Did not raise Type in: ' + stmt)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000831
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000832 self.assertEqual([tuple(list(pair)) for pair in zip_longest('abc', 'def')],
Thomas Wouterscf297e42007-02-23 15:07:44 +0000833 list(zip('abc', 'def')))
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000834 self.assertEqual([pair for pair in zip_longest('abc', 'def')],
Thomas Wouterscf297e42007-02-23 15:07:44 +0000835 list(zip('abc', 'def')))
Alex Gaynore151d212011-07-17 16:21:30 -0700836
837 @support.impl_detail("tuple reuse is specific to CPython")
838 def test_zip_longest_tuple_reuse(self):
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000839 ids = list(map(id, zip_longest('abc', 'def')))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000840 self.assertEqual(min(ids), max(ids))
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000841 ids = list(map(id, list(zip_longest('abc', 'def'))))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000842 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
843
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000844 def test_zip_longest_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200845 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
846 self.pickletest(proto, zip_longest("abc", "def"))
847 self.pickletest(proto, zip_longest("abc", "defgh"))
848 self.pickletest(proto, zip_longest("abc", "defgh", fillvalue=1))
849 self.pickletest(proto, zip_longest("", "defgh"))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000850
Raymond Hettingerfc438512009-11-01 20:55:33 +0000851 def test_bug_7244(self):
852
853 class Repeater:
854 # this class is similar to itertools.repeat
855 def __init__(self, o, t, e):
856 self.o = o
857 self.t = int(t)
858 self.e = e
859 def __iter__(self): # its iterator is itself
860 return self
861 def __next__(self):
862 if self.t > 0:
863 self.t -= 1
864 return self.o
865 else:
866 raise self.e
867
868 # Formerly this code in would fail in debug mode
869 # with Undetected Error and Stop Iteration
870 r1 = Repeater(1, 3, StopIteration)
871 r2 = Repeater(2, 4, StopIteration)
872 def run(r1, r2):
873 result = []
874 for i, j in zip_longest(r1, r2, fillvalue=0):
875 with support.captured_output('stdout'):
876 print((i, j))
877 result.append((i, j))
878 return result
879 self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])
880
881 # Formerly, the RuntimeError would be lost
882 # and StopIteration would stop as expected
883 r1 = Repeater(1, 3, RuntimeError)
884 r2 = Repeater(2, 4, StopIteration)
885 it = zip_longest(r1, r2, fillvalue=0)
886 self.assertEqual(next(it), (1, 2))
887 self.assertEqual(next(it), (1, 2))
888 self.assertEqual(next(it), (1, 2))
889 self.assertRaises(RuntimeError, next, it)
890
Christian Heimesc3f30c42008-02-22 16:37:40 +0000891 def test_product(self):
892 for args, result in [
Christian Heimes78644762008-03-04 23:39:23 +0000893 ([], [()]), # zero iterables
Christian Heimesc3f30c42008-02-22 16:37:40 +0000894 (['ab'], [('a',), ('b',)]), # one iterable
895 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
896 ([range(0), range(2), range(3)], []), # first iterable with zero length
897 ([range(2), range(0), range(3)], []), # middle iterable with zero length
898 ([range(2), range(3), range(0)], []), # last iterable with zero length
899 ]:
900 self.assertEqual(list(product(*args)), result)
Christian Heimesf16baeb2008-02-29 14:57:44 +0000901 for r in range(4):
902 self.assertEqual(list(product(*(args*r))),
903 list(product(*args, **dict(repeat=r))))
Christian Heimesc3f30c42008-02-22 16:37:40 +0000904 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
905 self.assertRaises(TypeError, product, range(6), None)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000906
907 def product1(*args, **kwds):
908 pools = list(map(tuple, args)) * kwds.get('repeat', 1)
909 n = len(pools)
910 if n == 0:
911 yield ()
912 return
913 if any(len(pool) == 0 for pool in pools):
914 return
915 indices = [0] * n
916 yield tuple(pool[i] for pool, i in zip(pools, indices))
917 while 1:
918 for i in reversed(range(n)): # right to left
919 if indices[i] == len(pools[i]) - 1:
920 continue
921 indices[i] += 1
922 for j in range(i+1, n):
923 indices[j] = 0
924 yield tuple(pool[i] for pool, i in zip(pools, indices))
925 break
926 else:
927 return
928
929 def product2(*args, **kwds):
930 'Pure python version used in docs'
931 pools = list(map(tuple, args)) * kwds.get('repeat', 1)
932 result = [[]]
933 for pool in pools:
934 result = [x+[y] for x in result for y in pool]
935 for prod in result:
936 yield tuple(prod)
937
Christian Heimesc3f30c42008-02-22 16:37:40 +0000938 argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3),
939 set('abcdefg'), range(11), tuple(range(13))]
940 for i in range(100):
941 args = [random.choice(argtypes) for j in range(random.randrange(5))]
Christian Heimes78644762008-03-04 23:39:23 +0000942 expected_len = prod(map(len, args))
943 self.assertEqual(len(list(product(*args))), expected_len)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000944 self.assertEqual(list(product(*args)), list(product1(*args)))
945 self.assertEqual(list(product(*args)), list(product2(*args)))
Christian Heimesc3f30c42008-02-22 16:37:40 +0000946 args = map(iter, args)
Christian Heimes78644762008-03-04 23:39:23 +0000947 self.assertEqual(len(list(product(*args))), expected_len)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000948
Alex Gaynore151d212011-07-17 16:21:30 -0700949 @support.impl_detail("tuple reuse is specific to CPython")
950 def test_product_tuple_reuse(self):
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000951 self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
952 self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000953
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000954 def test_product_pickling(self):
955 # check copy, deepcopy, pickle
956 for args, result in [
957 ([], [()]), # zero iterables
958 (['ab'], [('a',), ('b',)]), # one iterable
959 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
960 ([range(0), range(2), range(3)], []), # first iterable with zero length
961 ([range(2), range(0), range(3)], []), # middle iterable with zero length
962 ([range(2), range(3), range(0)], []), # last iterable with zero length
963 ]:
964 self.assertEqual(list(copy.copy(product(*args))), result)
965 self.assertEqual(list(copy.deepcopy(product(*args))), result)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200966 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
967 self.pickletest(proto, product(*args))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000968
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000969 def test_repeat(self):
Raymond Hettingerf4bb7f22009-02-19 02:44:01 +0000970 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
Guido van Rossum805365e2007-05-07 22:24:25 +0000971 self.assertEqual(lzip(range(3),repeat('a')),
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000972 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000973 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger02420702003-06-29 20:36:23 +0000974 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000975 self.assertEqual(list(repeat('a', 0)), [])
976 self.assertEqual(list(repeat('a', -3)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000977 self.assertRaises(TypeError, repeat)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000978 self.assertRaises(TypeError, repeat, None, 3, 4)
979 self.assertRaises(TypeError, repeat, None, 'a')
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000980 r = repeat(1+0j)
981 self.assertEqual(repr(r), 'repeat((1+0j))')
982 r = repeat(1+0j, 5)
983 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
984 list(r)
985 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000986
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000987 # check copy, deepcopy, pickle
988 c = repeat(object='a', times=10)
989 self.assertEqual(next(c), 'a')
990 self.assertEqual(take(2, copy.copy(c)), list('a' * 2))
991 self.assertEqual(take(2, copy.deepcopy(c)), list('a' * 2))
Serhiy Storchakabad12572014-12-15 14:03:42 +0200992 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
993 self.pickletest(proto, repeat(object='a', times=10))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000994
Raymond Hettinger97d35552014-06-24 21:36:58 -0700995 def test_repeat_with_negative_times(self):
996 self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
997 self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
998 self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
999 self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
1000
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001001 def test_map(self):
1002 self.assertEqual(list(map(operator.pow, range(3), range(1,7))),
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001003 [0**1, 1**2, 2**3])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001004 self.assertEqual(list(map(tupleize, 'abc', range(5))),
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001005 [('a',0),('b',1),('c',2)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001006 self.assertEqual(list(map(tupleize, 'abc', count())),
Raymond Hettinger02420702003-06-29 20:36:23 +00001007 [('a',0),('b',1),('c',2)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001008 self.assertEqual(take(2,map(tupleize, 'abc', count())),
Raymond Hettinger02420702003-06-29 20:36:23 +00001009 [('a',0),('b',1)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001010 self.assertEqual(list(map(operator.pow, [])), [])
1011 self.assertRaises(TypeError, map)
1012 self.assertRaises(TypeError, list, map(None, range(3), range(3)))
1013 self.assertRaises(TypeError, map, operator.neg)
1014 self.assertRaises(TypeError, next, map(10, range(5)))
1015 self.assertRaises(ValueError, next, map(errfunc, [4], [5]))
1016 self.assertRaises(TypeError, next, map(onearg, [4], [5]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001017
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001018 # check copy, deepcopy, pickle
1019 ans = [('a',0),('b',1),('c',2)]
1020
1021 c = map(tupleize, 'abc', count())
1022 self.assertEqual(list(copy.copy(c)), ans)
1023
1024 c = map(tupleize, 'abc', count())
1025 self.assertEqual(list(copy.deepcopy(c)), ans)
1026
Serhiy Storchakabad12572014-12-15 14:03:42 +02001027 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1028 c = map(tupleize, 'abc', count())
1029 self.pickletest(proto, c)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001030
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001031 def test_starmap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001032 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
1033 [0**1, 1**2, 2**3])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001034 self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))),
Raymond Hettinger02420702003-06-29 20:36:23 +00001035 [0**1, 1**2, 2**3])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001036 self.assertEqual(list(starmap(operator.pow, [])), [])
Christian Heimes679db4a2008-01-18 09:56:22 +00001037 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
1038 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001039 self.assertRaises(TypeError, starmap)
1040 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001041 self.assertRaises(TypeError, next, starmap(10, [(4,5)]))
1042 self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)]))
1043 self.assertRaises(TypeError, next, starmap(onearg, [(4,5)]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001044
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001045 # check copy, deepcopy, pickle
1046 ans = [0**1, 1**2, 2**3]
1047
1048 c = starmap(operator.pow, zip(range(3), range(1,7)))
1049 self.assertEqual(list(copy.copy(c)), ans)
1050
1051 c = starmap(operator.pow, zip(range(3), range(1,7)))
1052 self.assertEqual(list(copy.deepcopy(c)), ans)
1053
Serhiy Storchakabad12572014-12-15 14:03:42 +02001054 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1055 c = starmap(operator.pow, zip(range(3), range(1,7)))
1056 self.pickletest(proto, c)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001057
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001058 def test_islice(self):
1059 for args in [ # islice(args) should agree with range(args)
1060 (10, 20, 3),
1061 (10, 3, 20),
1062 (10, 20),
1063 (10, 3),
1064 (20,)
1065 ]:
Guido van Rossum805365e2007-05-07 22:24:25 +00001066 self.assertEqual(list(islice(range(100), *args)),
1067 list(range(*args)))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001068
1069 for args, tgtargs in [ # Stop when seqn is exhausted
1070 ((10, 110, 3), ((10, 100, 3))),
1071 ((10, 110), ((10, 100))),
1072 ((110,), (100,))
1073 ]:
Guido van Rossum805365e2007-05-07 22:24:25 +00001074 self.assertEqual(list(islice(range(100), *args)),
1075 list(range(*tgtargs)))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001076
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001077 # Test stop=None
Guido van Rossum805365e2007-05-07 22:24:25 +00001078 self.assertEqual(list(islice(range(10), None)), list(range(10)))
1079 self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
1080 self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
1081 self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
1082 self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001083
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +00001084 # Test number of items consumed SF #1171417
1085 it = iter(range(10))
Guido van Rossum805365e2007-05-07 22:24:25 +00001086 self.assertEqual(list(islice(it, 3)), list(range(3)))
1087 self.assertEqual(list(it), list(range(3, 10)))
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +00001088
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001089 # Test invalid arguments
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001090 ra = range(10)
1091 self.assertRaises(TypeError, islice, ra)
1092 self.assertRaises(TypeError, islice, ra, 1, 2, 3, 4)
1093 self.assertRaises(ValueError, islice, ra, -5, 10, 1)
1094 self.assertRaises(ValueError, islice, ra, 1, -5, -1)
1095 self.assertRaises(ValueError, islice, ra, 1, 10, -1)
1096 self.assertRaises(ValueError, islice, ra, 1, 10, 0)
1097 self.assertRaises(ValueError, islice, ra, 'a')
1098 self.assertRaises(ValueError, islice, ra, 'a', 1)
1099 self.assertRaises(ValueError, islice, ra, 1, 'a')
1100 self.assertRaises(ValueError, islice, ra, 'a', 1, 1)
1101 self.assertRaises(ValueError, islice, ra, 1, 'a', 1)
Guido van Rossum360e4b82007-05-14 22:51:27 +00001102 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001103
Raymond Hettinger69b34bf2010-11-30 02:49:29 +00001104 # Issue #10323: Less islice in a predictable state
1105 c = count()
1106 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
1107 self.assertEqual(next(c), 3)
1108
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001109 # check copy, deepcopy, pickle
1110 for args in [ # islice(args) should agree with range(args)
1111 (10, 20, 3),
1112 (10, 3, 20),
1113 (10, 20),
1114 (10, 3),
1115 (20,)
1116 ]:
1117 self.assertEqual(list(copy.copy(islice(range(100), *args))),
1118 list(range(*args)))
1119 self.assertEqual(list(copy.deepcopy(islice(range(100), *args))),
1120 list(range(*args)))
Serhiy Storchakabad12572014-12-15 14:03:42 +02001121 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1122 self.pickletest(proto, islice(range(100), *args))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001123
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001124 # Issue #21321: check source iterator is not referenced
1125 # from islice() after the latter has been exhausted
1126 it = (x for x in (1, 2))
1127 wr = weakref.ref(it)
1128 it = islice(it, 1)
1129 self.assertIsNotNone(wr())
1130 list(it) # exhaust the iterator
Benjamin Peterson8e163512014-08-24 18:07:28 -05001131 support.gc_collect()
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001132 self.assertIsNone(wr())
1133
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001134 def test_takewhile(self):
1135 data = [1, 3, 5, 20, 2, 4, 6, 8]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001136 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001137 self.assertEqual(list(takewhile(underten, [])), [])
1138 self.assertRaises(TypeError, takewhile)
1139 self.assertRaises(TypeError, takewhile, operator.pow)
1140 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001141 self.assertRaises(TypeError, next, takewhile(10, [(4,5)]))
1142 self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)]))
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001143 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
1144 self.assertEqual(list(t), [1, 1, 1])
Georg Brandla18af4e2007-04-21 15:47:16 +00001145 self.assertRaises(StopIteration, next, t)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001146
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001147 # check copy, deepcopy, pickle
1148 self.assertEqual(list(copy.copy(takewhile(underten, data))), [1, 3, 5])
1149 self.assertEqual(list(copy.deepcopy(takewhile(underten, data))),
1150 [1, 3, 5])
Serhiy Storchakabad12572014-12-15 14:03:42 +02001151 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1152 self.pickletest(proto, takewhile(underten, data))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001153
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001154 def test_dropwhile(self):
1155 data = [1, 3, 5, 20, 2, 4, 6, 8]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001156 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00001157 self.assertEqual(list(dropwhile(underten, [])), [])
1158 self.assertRaises(TypeError, dropwhile)
1159 self.assertRaises(TypeError, dropwhile, operator.pow)
1160 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
Georg Brandla18af4e2007-04-21 15:47:16 +00001161 self.assertRaises(TypeError, next, dropwhile(10, [(4,5)]))
1162 self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001163
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001164 # check copy, deepcopy, pickle
1165 self.assertEqual(list(copy.copy(dropwhile(underten, data))), [20, 2, 4, 6, 8])
1166 self.assertEqual(list(copy.deepcopy(dropwhile(underten, data))),
1167 [20, 2, 4, 6, 8])
Serhiy Storchakabad12572014-12-15 14:03:42 +02001168 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1169 self.pickletest(proto, dropwhile(underten, data))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001170
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001171 def test_tee(self):
Raymond Hettingerad983e72003-11-12 14:32:26 +00001172 n = 200
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001173
1174 a, b = tee([]) # test empty iterator
1175 self.assertEqual(list(a), [])
1176 self.assertEqual(list(b), [])
1177
1178 a, b = tee(irange(n)) # test 100% interleaved
Guido van Rossum801f0d72006-08-24 19:48:10 +00001179 self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001180
1181 a, b = tee(irange(n)) # test 0% interleaved
Guido van Rossum805365e2007-05-07 22:24:25 +00001182 self.assertEqual(list(a), list(range(n)))
1183 self.assertEqual(list(b), list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001184
1185 a, b = tee(irange(n)) # test dealloc of leading iterator
Guido van Rossum805365e2007-05-07 22:24:25 +00001186 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001187 self.assertEqual(next(a), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001188 del a
Guido van Rossum805365e2007-05-07 22:24:25 +00001189 self.assertEqual(list(b), list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001190
1191 a, b = tee(irange(n)) # test dealloc of trailing iterator
Guido van Rossum805365e2007-05-07 22:24:25 +00001192 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001193 self.assertEqual(next(a), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001194 del b
Guido van Rossum805365e2007-05-07 22:24:25 +00001195 self.assertEqual(list(a), list(range(100, n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001196
Guido van Rossum805365e2007-05-07 22:24:25 +00001197 for j in range(5): # test randomly interleaved
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001198 order = [0]*n + [1]*n
1199 random.shuffle(order)
1200 lists = ([], [])
1201 its = tee(irange(n))
1202 for i in order:
Georg Brandla18af4e2007-04-21 15:47:16 +00001203 value = next(its[i])
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001204 lists[i].append(value)
Guido van Rossum805365e2007-05-07 22:24:25 +00001205 self.assertEqual(lists[0], list(range(n)))
1206 self.assertEqual(lists[1], list(range(n)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001207
Raymond Hettingerad983e72003-11-12 14:32:26 +00001208 # test argument format checking
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001209 self.assertRaises(TypeError, tee)
1210 self.assertRaises(TypeError, tee, 3)
1211 self.assertRaises(TypeError, tee, [1,2], 'x')
Raymond Hettingerad983e72003-11-12 14:32:26 +00001212 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001213
Raymond Hettingerad983e72003-11-12 14:32:26 +00001214 # tee object should be instantiable
1215 a, b = tee('abc')
1216 c = type(a)('def')
1217 self.assertEqual(list(c), list('def'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +00001218
Raymond Hettingerad983e72003-11-12 14:32:26 +00001219 # test long-lagged and multi-way split
Guido van Rossum805365e2007-05-07 22:24:25 +00001220 a, b, c = tee(range(2000), 3)
1221 for i in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +00001222 self.assertEqual(next(a), i)
Guido van Rossum805365e2007-05-07 22:24:25 +00001223 self.assertEqual(list(b), list(range(2000)))
1224 self.assertEqual([next(c), next(c)], list(range(2)))
1225 self.assertEqual(list(a), list(range(100,2000)))
1226 self.assertEqual(list(c), list(range(2,2000)))
Raymond Hettingerad983e72003-11-12 14:32:26 +00001227
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001228 # test values of n
1229 self.assertRaises(TypeError, tee, 'abc', 'invalid')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001230 self.assertRaises(ValueError, tee, [], -1)
Guido van Rossum805365e2007-05-07 22:24:25 +00001231 for n in range(5):
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001232 result = tee('abc', n)
1233 self.assertEqual(type(result), tuple)
1234 self.assertEqual(len(result), n)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001235 self.assertEqual([list(x) for x in result], [list('abc')]*n)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001236
Raymond Hettingerad983e72003-11-12 14:32:26 +00001237 # tee pass-through to copyable iterator
1238 a, b = tee('abc')
1239 c, d = tee(a)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001240 self.assertTrue(a is c)
Raymond Hettingerad983e72003-11-12 14:32:26 +00001241
Raymond Hettinger4cda01e2004-09-28 04:45:28 +00001242 # test tee_new
1243 t1, t2 = tee('abc')
1244 tnew = type(t1)
1245 self.assertRaises(TypeError, tnew)
1246 self.assertRaises(TypeError, tnew, 10)
1247 t3 = tnew(t1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001248 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +00001249
Raymond Hettingera9f60922004-10-17 16:40:14 +00001250 # test that tee objects are weak referencable
Guido van Rossum805365e2007-05-07 22:24:25 +00001251 a, b = tee(range(10))
Antoine Pitrou26f82ef2014-04-29 12:13:46 +02001252 p = weakref.proxy(a)
Raymond Hettingera9f60922004-10-17 16:40:14 +00001253 self.assertEqual(getattr(p, '__class__'), type(b))
1254 del a
1255 self.assertRaises(ReferenceError, getattr, p, '__class__')
1256
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001257 ans = list('abc')
1258 long_ans = list(range(10000))
1259
1260 # check copy
1261 a, b = tee('abc')
1262 self.assertEqual(list(copy.copy(a)), ans)
1263 self.assertEqual(list(copy.copy(b)), ans)
1264 a, b = tee(list(range(10000)))
1265 self.assertEqual(list(copy.copy(a)), long_ans)
1266 self.assertEqual(list(copy.copy(b)), long_ans)
1267
1268 # check partially consumed copy
1269 a, b = tee('abc')
1270 take(2, a)
1271 take(1, b)
1272 self.assertEqual(list(copy.copy(a)), ans[2:])
1273 self.assertEqual(list(copy.copy(b)), ans[1:])
1274 self.assertEqual(list(a), ans[2:])
1275 self.assertEqual(list(b), ans[1:])
1276 a, b = tee(range(10000))
1277 take(100, a)
1278 take(60, b)
1279 self.assertEqual(list(copy.copy(a)), long_ans[100:])
1280 self.assertEqual(list(copy.copy(b)), long_ans[60:])
1281 self.assertEqual(list(a), long_ans[100:])
1282 self.assertEqual(list(b), long_ans[60:])
1283
1284 # check deepcopy
1285 a, b = tee('abc')
1286 self.assertEqual(list(copy.deepcopy(a)), ans)
1287 self.assertEqual(list(copy.deepcopy(b)), ans)
1288 self.assertEqual(list(a), ans)
1289 self.assertEqual(list(b), ans)
1290 a, b = tee(range(10000))
1291 self.assertEqual(list(copy.deepcopy(a)), long_ans)
1292 self.assertEqual(list(copy.deepcopy(b)), long_ans)
1293 self.assertEqual(list(a), long_ans)
1294 self.assertEqual(list(b), long_ans)
1295
1296 # check partially consumed deepcopy
1297 a, b = tee('abc')
1298 take(2, a)
1299 take(1, b)
1300 self.assertEqual(list(copy.deepcopy(a)), ans[2:])
1301 self.assertEqual(list(copy.deepcopy(b)), ans[1:])
1302 self.assertEqual(list(a), ans[2:])
1303 self.assertEqual(list(b), ans[1:])
1304 a, b = tee(range(10000))
1305 take(100, a)
1306 take(60, b)
1307 self.assertEqual(list(copy.deepcopy(a)), long_ans[100:])
1308 self.assertEqual(list(copy.deepcopy(b)), long_ans[60:])
1309 self.assertEqual(list(a), long_ans[100:])
1310 self.assertEqual(list(b), long_ans[60:])
1311
1312 # check pickle
Serhiy Storchakabad12572014-12-15 14:03:42 +02001313 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1314 self.pickletest(proto, iter(tee('abc')))
1315 a, b = tee('abc')
1316 self.pickletest(proto, a, compare=ans)
1317 self.pickletest(proto, b, compare=ans)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001318
Serhiy Storchakaa3e91282013-01-25 13:19:31 +02001319 # Issue 13454: Crash when deleting backward iterator from tee()
1320 def test_tee_del_backward(self):
Serhiy Storchaka5bb893c2013-01-26 11:52:06 +02001321 forward, backward = tee(repeat(None, 20000000))
1322 any(forward) # exhaust the iterator
Serhiy Storchakaa3e91282013-01-25 13:19:31 +02001323 del backward
1324
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001325 def test_StopIteration(self):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001326 self.assertRaises(StopIteration, next, zip())
Raymond Hettingerb5a42082003-08-08 05:10:41 +00001327
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001328 for f in (chain, cycle, zip, groupby):
Georg Brandla18af4e2007-04-21 15:47:16 +00001329 self.assertRaises(StopIteration, next, f([]))
1330 self.assertRaises(StopIteration, next, f(StopNow()))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001331
Georg Brandla18af4e2007-04-21 15:47:16 +00001332 self.assertRaises(StopIteration, next, islice([], None))
1333 self.assertRaises(StopIteration, next, islice(StopNow(), None))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001334
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001335 p, q = tee([])
Georg Brandla18af4e2007-04-21 15:47:16 +00001336 self.assertRaises(StopIteration, next, p)
1337 self.assertRaises(StopIteration, next, q)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001338 p, q = tee(StopNow())
Georg Brandla18af4e2007-04-21 15:47:16 +00001339 self.assertRaises(StopIteration, next, p)
1340 self.assertRaises(StopIteration, next, q)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001341
Georg Brandla18af4e2007-04-21 15:47:16 +00001342 self.assertRaises(StopIteration, next, repeat(None, 0))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001343
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001344 for f in (filter, filterfalse, map, takewhile, dropwhile, starmap):
Georg Brandla18af4e2007-04-21 15:47:16 +00001345 self.assertRaises(StopIteration, next, f(lambda x:x, []))
1346 self.assertRaises(StopIteration, next, f(lambda x:x, StopNow()))
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001347
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001348class TestExamples(unittest.TestCase):
1349
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001350 def test_accumulate(self):
Raymond Hettinger482ba772010-12-01 22:48:00 +00001351 self.assertEqual(list(accumulate([1,2,3,4,5])), [1, 3, 6, 10, 15])
1352
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001353 def test_accumulate_reducible(self):
1354 # check copy, deepcopy, pickle
1355 data = [1, 2, 3, 4, 5]
1356 accumulated = [1, 3, 6, 10, 15]
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001357
Serhiy Storchakabad12572014-12-15 14:03:42 +02001358 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1359 it = accumulate(data)
1360 self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[:])
1361 self.assertEqual(next(it), 1)
1362 self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[1:])
1363 it = accumulate(data)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001364 self.assertEqual(next(it), 1)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001365 self.assertEqual(list(copy.deepcopy(it)), accumulated[1:])
1366 self.assertEqual(list(copy.copy(it)), accumulated[1:])
1367
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001368 def test_chain(self):
1369 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
1370
1371 def test_chain_from_iterable(self):
1372 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
1373
1374 def test_combinations(self):
1375 self.assertEqual(list(combinations('ABCD', 2)),
1376 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
1377 self.assertEqual(list(combinations(range(4), 3)),
1378 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
1379
Raymond Hettingerd07d9392009-01-27 04:20:44 +00001380 def test_combinations_with_replacement(self):
1381 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
1382 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
1383
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001384 def test_compress(self):
1385 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
1386
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001387 def test_count(self):
1388 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
1389
1390 def test_cycle(self):
1391 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
1392
1393 def test_dropwhile(self):
1394 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
1395
1396 def test_groupby(self):
1397 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
1398 list('ABCDAB'))
1399 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
1400 [list('AAAA'), list('BBB'), list('CC'), list('D')])
1401
1402 def test_filter(self):
1403 self.assertEqual(list(filter(lambda x: x%2, range(10))), [1,3,5,7,9])
1404
1405 def test_filterfalse(self):
1406 self.assertEqual(list(filterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
1407
1408 def test_map(self):
1409 self.assertEqual(list(map(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
1410
1411 def test_islice(self):
1412 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
1413 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
1414 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
1415 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
1416
1417 def test_zip(self):
1418 self.assertEqual(list(zip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
1419
1420 def test_zip_longest(self):
1421 self.assertEqual(list(zip_longest('ABCD', 'xy', fillvalue='-')),
1422 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
1423
1424 def test_permutations(self):
1425 self.assertEqual(list(permutations('ABCD', 2)),
1426 list(map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split())))
1427 self.assertEqual(list(permutations(range(3))),
1428 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
1429
1430 def test_product(self):
1431 self.assertEqual(list(product('ABCD', 'xy')),
1432 list(map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split())))
1433 self.assertEqual(list(product(range(2), repeat=3)),
1434 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1435 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1436
1437 def test_repeat(self):
1438 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1439
1440 def test_stapmap(self):
1441 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1442 [32, 9, 1000])
1443
1444 def test_takewhile(self):
1445 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1446
1447
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001448class TestGC(unittest.TestCase):
1449
1450 def makecycle(self, iterator, container):
1451 container.append(iterator)
Georg Brandla18af4e2007-04-21 15:47:16 +00001452 next(iterator)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001453 del container, iterator
1454
Raymond Hettinger482ba772010-12-01 22:48:00 +00001455 def test_accumulate(self):
1456 a = []
1457 self.makecycle(accumulate([1,2,a,3]), a)
1458
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001459 def test_chain(self):
1460 a = []
1461 self.makecycle(chain(a), a)
1462
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001463 def test_chain_from_iterable(self):
1464 a = []
1465 self.makecycle(chain.from_iterable([a]), a)
1466
1467 def test_combinations(self):
1468 a = []
1469 self.makecycle(combinations([1,2,a,3], 3), a)
1470
Raymond Hettingerd07d9392009-01-27 04:20:44 +00001471 def test_combinations_with_replacement(self):
1472 a = []
1473 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1474
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001475 def test_compress(self):
1476 a = []
1477 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1478
Raymond Hettingerd6280f42009-02-16 20:50:56 +00001479 def test_count(self):
1480 a = []
1481 Int = type('Int', (int,), dict(x=a))
1482 self.makecycle(count(Int(0), Int(1)), a)
1483
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001484 def test_cycle(self):
1485 a = []
1486 self.makecycle(cycle([a]*2), a)
1487
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001488 def test_dropwhile(self):
1489 a = []
1490 self.makecycle(dropwhile(bool, [0, a, a]), a)
1491
1492 def test_groupby(self):
1493 a = []
1494 self.makecycle(groupby([a]*2, lambda x:x), a)
1495
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001496 def test_issue2246(self):
1497 # Issue 2246 -- the _grouper iterator was not included in GC
1498 n = 10
1499 keyfunc = lambda x: x
1500 for i, j in groupby(range(n), key=keyfunc):
1501 keyfunc.__dict__.setdefault('x',[]).append(j)
1502
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001503 def test_filter(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001504 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001505 self.makecycle(filter(lambda x:True, [a]*2), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001506
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001507 def test_filterfalse(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001508 a = []
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001509 self.makecycle(filterfalse(lambda x:False, a), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001510
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001511 def test_zip(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001512 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001513 self.makecycle(zip([a]*2, [a]*3), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001514
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001515 def test_zip_longest(self):
1516 a = []
1517 self.makecycle(zip_longest([a]*2, [a]*3), a)
1518 b = [a, None]
1519 self.makecycle(zip_longest([a]*2, [a]*3, fillvalue=b), a)
1520
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001521 def test_map(self):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001522 a = []
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001523 self.makecycle(map(lambda x:x, [a]*2), a)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001524
1525 def test_islice(self):
1526 a = []
1527 self.makecycle(islice([a]*2, None), a)
1528
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001529 def test_permutations(self):
1530 a = []
1531 self.makecycle(permutations([1,2,a,3], 3), a)
1532
1533 def test_product(self):
1534 a = []
1535 self.makecycle(product([1,2,a,3], repeat=3), a)
1536
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001537 def test_repeat(self):
1538 a = []
1539 self.makecycle(repeat(a), a)
1540
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001541 def test_starmap(self):
1542 a = []
1543 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1544
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001545 def test_takewhile(self):
1546 a = []
1547 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1548
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001549def R(seqn):
1550 'Regular generator'
1551 for i in seqn:
1552 yield i
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001553
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001554class G:
1555 'Sequence using __getitem__'
1556 def __init__(self, seqn):
1557 self.seqn = seqn
1558 def __getitem__(self, i):
1559 return self.seqn[i]
1560
1561class I:
1562 'Sequence using iterator protocol'
1563 def __init__(self, seqn):
1564 self.seqn = seqn
1565 self.i = 0
1566 def __iter__(self):
1567 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001568 def __next__(self):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001569 if self.i >= len(self.seqn): raise StopIteration
1570 v = self.seqn[self.i]
1571 self.i += 1
1572 return v
1573
1574class Ig:
1575 'Sequence using iterator protocol defined with a generator'
1576 def __init__(self, seqn):
1577 self.seqn = seqn
1578 self.i = 0
1579 def __iter__(self):
1580 for val in self.seqn:
1581 yield val
1582
1583class X:
1584 'Missing __getitem__ and __iter__'
1585 def __init__(self, seqn):
1586 self.seqn = seqn
1587 self.i = 0
Georg Brandla18af4e2007-04-21 15:47:16 +00001588 def __next__(self):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001589 if self.i >= len(self.seqn): raise StopIteration
1590 v = self.seqn[self.i]
1591 self.i += 1
1592 return v
1593
1594class N:
Georg Brandla18af4e2007-04-21 15:47:16 +00001595 'Iterator missing __next__()'
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001596 def __init__(self, seqn):
1597 self.seqn = seqn
1598 self.i = 0
1599 def __iter__(self):
1600 return self
1601
1602class E:
1603 'Test propagation of exceptions'
1604 def __init__(self, seqn):
1605 self.seqn = seqn
1606 self.i = 0
1607 def __iter__(self):
1608 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001609 def __next__(self):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +00001610 3 // 0
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001611
1612class S:
1613 'Test immediate stop'
1614 def __init__(self, seqn):
1615 pass
1616 def __iter__(self):
1617 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00001618 def __next__(self):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001619 raise StopIteration
1620
1621def L(seqn):
1622 'Test multiple tiers of iterators'
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001623 return chain(map(lambda x:x, R(Ig(G(seqn)))))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001624
1625
1626class TestVariousIteratorArgs(unittest.TestCase):
1627
Raymond Hettinger482ba772010-12-01 22:48:00 +00001628 def test_accumulate(self):
1629 s = [1,2,3,4,5]
1630 r = [1,3,6,10,15]
1631 n = len(s)
1632 for g in (G, I, Ig, L, R):
1633 self.assertEqual(list(accumulate(g(s))), r)
1634 self.assertEqual(list(accumulate(S(s))), [])
1635 self.assertRaises(TypeError, accumulate, X(s))
1636 self.assertRaises(TypeError, accumulate, N(s))
1637 self.assertRaises(ZeroDivisionError, list, accumulate(E(s)))
1638
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001639 def test_chain(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001640 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001641 for g in (G, I, Ig, S, L, R):
1642 self.assertEqual(list(chain(g(s))), list(g(s)))
1643 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
Christian Heimesf16baeb2008-02-29 14:57:44 +00001644 self.assertRaises(TypeError, list, chain(X(s)))
Mark Dickinson26a96fa2008-03-01 02:27:46 +00001645 self.assertRaises(TypeError, list, chain(N(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001646 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
1647
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001648 def test_compress(self):
1649 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
1650 n = len(s)
1651 for g in (G, I, Ig, S, L, R):
1652 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
1653 self.assertRaises(TypeError, compress, X(s), repeat(1))
1654 self.assertRaises(TypeError, compress, N(s), repeat(1))
1655 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
1656
Christian Heimesc3f30c42008-02-22 16:37:40 +00001657 def test_product(self):
1658 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
1659 self.assertRaises(TypeError, product, X(s))
1660 self.assertRaises(TypeError, product, N(s))
1661 self.assertRaises(ZeroDivisionError, product, E(s))
1662
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001663 def test_cycle(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001664 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001665 for g in (G, I, Ig, S, L, R):
1666 tgtlen = len(s) * 3
1667 expected = list(g(s))*3
1668 actual = list(islice(cycle(g(s)), tgtlen))
1669 self.assertEqual(actual, expected)
1670 self.assertRaises(TypeError, cycle, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001671 self.assertRaises(TypeError, cycle, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001672 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
1673
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001674 def test_groupby(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001675 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001676 for g in (G, I, Ig, S, L, R):
1677 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
1678 self.assertRaises(TypeError, groupby, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001679 self.assertRaises(TypeError, groupby, N(s))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001680 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
1681
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001682 def test_filter(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001683 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001684 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001685 self.assertEqual(list(filter(isEven, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001686 [x for x in g(s) if isEven(x)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001687 self.assertRaises(TypeError, filter, isEven, X(s))
1688 self.assertRaises(TypeError, filter, isEven, N(s))
1689 self.assertRaises(ZeroDivisionError, list, filter(isEven, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001690
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001691 def test_filterfalse(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001692 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001693 for g in (G, I, Ig, S, L, R):
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001694 self.assertEqual(list(filterfalse(isEven, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001695 [x for x in g(s) if isOdd(x)])
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001696 self.assertRaises(TypeError, filterfalse, isEven, X(s))
1697 self.assertRaises(TypeError, filterfalse, isEven, N(s))
1698 self.assertRaises(ZeroDivisionError, list, filterfalse(isEven, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001699
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001700 def test_zip(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001701 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001702 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001703 self.assertEqual(list(zip(g(s))), lzip(g(s)))
1704 self.assertEqual(list(zip(g(s), g(s))), lzip(g(s), g(s)))
1705 self.assertRaises(TypeError, zip, X(s))
1706 self.assertRaises(TypeError, zip, N(s))
1707 self.assertRaises(ZeroDivisionError, list, zip(E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001708
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001709 def test_ziplongest(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001710 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001711 for g in (G, I, Ig, S, L, R):
Raymond Hettingerb0002d22008-03-13 01:41:43 +00001712 self.assertEqual(list(zip_longest(g(s))), list(zip(g(s))))
1713 self.assertEqual(list(zip_longest(g(s), g(s))), list(zip(g(s), g(s))))
1714 self.assertRaises(TypeError, zip_longest, X(s))
1715 self.assertRaises(TypeError, zip_longest, N(s))
1716 self.assertRaises(ZeroDivisionError, list, zip_longest(E(s)))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001717
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001718 def test_map(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001719 for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001720 for g in (G, I, Ig, S, L, R):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001721 self.assertEqual(list(map(onearg, g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001722 [onearg(x) for x in g(s)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001723 self.assertEqual(list(map(operator.pow, g(s), g(s))),
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001724 [x**x for x in g(s)])
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001725 self.assertRaises(TypeError, map, onearg, X(s))
1726 self.assertRaises(TypeError, map, onearg, N(s))
1727 self.assertRaises(ZeroDivisionError, list, map(onearg, E(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001728
1729 def test_islice(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001730 for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001731 for g in (G, I, Ig, S, L, R):
1732 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
1733 self.assertRaises(TypeError, islice, X(s), 10)
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001734 self.assertRaises(TypeError, islice, N(s), 10)
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001735 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
1736
1737 def test_starmap(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001738 for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001739 for g in (G, I, Ig, S, L, R):
Guido van Rossum801f0d72006-08-24 19:48:10 +00001740 ss = lzip(s, s)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001741 self.assertEqual(list(starmap(operator.pow, g(ss))),
1742 [x**x for x in g(s)])
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001743 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001744 self.assertRaises(TypeError, starmap, operator.pow, N(ss))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001745 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
1746
1747 def test_takewhile(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001748 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001749 for g in (G, I, Ig, S, L, R):
1750 tgt = []
1751 for elem in g(s):
1752 if not isEven(elem): break
1753 tgt.append(elem)
1754 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
1755 self.assertRaises(TypeError, takewhile, isEven, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001756 self.assertRaises(TypeError, takewhile, isEven, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001757 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
1758
1759 def test_dropwhile(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001760 for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001761 for g in (G, I, Ig, S, L, R):
1762 tgt = []
1763 for elem in g(s):
1764 if not tgt and isOdd(elem): continue
1765 tgt.append(elem)
1766 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
1767 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001768 self.assertRaises(TypeError, dropwhile, isOdd, N(s))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001769 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
1770
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001771 def test_tee(self):
Guido van Rossum805365e2007-05-07 22:24:25 +00001772 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001773 for g in (G, I, Ig, S, L, R):
1774 it1, it2 = tee(g(s))
1775 self.assertEqual(list(it1), list(g(s)))
1776 self.assertEqual(list(it2), list(g(s)))
1777 self.assertRaises(TypeError, tee, X(s))
Thomas Wouters8690c4e2006-04-15 09:07:20 +00001778 self.assertRaises(TypeError, tee, N(s))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001779 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
1780
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001781class LengthTransparency(unittest.TestCase):
1782
1783 def test_repeat(self):
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001784 self.assertEqual(operator.length_hint(repeat(None, 50)), 50)
Raymond Hettinger97d35552014-06-24 21:36:58 -07001785 self.assertEqual(operator.length_hint(repeat(None, 0)), 0)
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001786 self.assertEqual(operator.length_hint(repeat(None), 12), 12)
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001787
Raymond Hettinger97d35552014-06-24 21:36:58 -07001788 def test_repeat_with_negative_times(self):
1789 self.assertEqual(operator.length_hint(repeat(None, -1)), 0)
1790 self.assertEqual(operator.length_hint(repeat(None, -2)), 0)
1791 self.assertEqual(operator.length_hint(repeat(None, times=-1)), 0)
1792 self.assertEqual(operator.length_hint(repeat(None, times=-2)), 0)
1793
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001794class RegressionTests(unittest.TestCase):
1795
1796 def test_sf_793826(self):
1797 # Fix Armin Rigo's successful efforts to wreak havoc
1798
1799 def mutatingtuple(tuple1, f, tuple2):
1800 # this builds a tuple t which is a copy of tuple1,
1801 # then calls f(t), then mutates t to be equal to tuple2
1802 # (needs len(tuple1) == len(tuple2)).
1803 def g(value, first=[1]):
1804 if first:
1805 del first[:]
Georg Brandla18af4e2007-04-21 15:47:16 +00001806 f(next(z))
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001807 return value
1808 items = list(tuple2)
1809 items[1:1] = list(tuple1)
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001810 gen = map(g, items)
1811 z = zip(*[gen]*len(tuple1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001812 next(z)
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001813
1814 def f(t):
1815 global T
1816 T = t
1817 first[:] = list(T)
1818
1819 first = []
1820 mutatingtuple((1,2,3), f, (4,5,6))
1821 second = list(T)
1822 self.assertEqual(first, second)
1823
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001824
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001825 def test_sf_950057(self):
1826 # Make sure that chain() and cycle() catch exceptions immediately
1827 # rather than when shifting between input sources
1828
1829 def gen1():
1830 hist.append(0)
1831 yield 1
1832 hist.append(1)
Tim Petersbeb7c0c2004-07-18 17:34:03 +00001833 raise AssertionError
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001834 hist.append(2)
1835
1836 def gen2(x):
1837 hist.append(3)
1838 yield 2
1839 hist.append(4)
1840 if x:
1841 raise StopIteration
1842
1843 hist = []
1844 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
1845 self.assertEqual(hist, [0,1])
1846
1847 hist = []
1848 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
1849 self.assertEqual(hist, [0,1])
1850
1851 hist = []
1852 self.assertRaises(AssertionError, list, cycle(gen1()))
1853 self.assertEqual(hist, [0,1])
1854
Thomas Woutersb2137042007-02-01 18:02:27 +00001855class SubclassWithKwargsTest(unittest.TestCase):
1856 def test_keywords_in_subclass(self):
1857 # count is not subclassable...
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001858 for cls in (repeat, zip, filter, filterfalse, chain, map,
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +00001859 starmap, islice, takewhile, dropwhile, cycle, compress):
Thomas Woutersb2137042007-02-01 18:02:27 +00001860 class Subclass(cls):
1861 def __init__(self, newarg=None, *args):
1862 cls.__init__(self, *args)
1863 try:
1864 Subclass(newarg=1)
1865 except TypeError as err:
1866 # we expect type errors because of wrong argument count
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001867 self.assertNotIn("does not take keyword arguments", err.args[0])
Thomas Woutersb2137042007-02-01 18:02:27 +00001868
Serhiy Storchaka2dae92a2013-12-09 17:45:57 +02001869@support.cpython_only
1870class SizeofTest(unittest.TestCase):
1871 def setUp(self):
1872 self.ssize_t = struct.calcsize('n')
1873
1874 check_sizeof = support.check_sizeof
1875
1876 def test_product_sizeof(self):
1877 basesize = support.calcobjsize('3Pi')
1878 check = self.check_sizeof
1879 check(product('ab', '12'), basesize + 2 * self.ssize_t)
1880 check(product(*(('abc',) * 10)), basesize + 10 * self.ssize_t)
1881
1882 def test_combinations_sizeof(self):
1883 basesize = support.calcobjsize('3Pni')
1884 check = self.check_sizeof
1885 check(combinations('abcd', 3), basesize + 3 * self.ssize_t)
1886 check(combinations(range(10), 4), basesize + 4 * self.ssize_t)
1887
1888 def test_combinations_with_replacement_sizeof(self):
1889 cwr = combinations_with_replacement
1890 basesize = support.calcobjsize('3Pni')
1891 check = self.check_sizeof
1892 check(cwr('abcd', 3), basesize + 3 * self.ssize_t)
1893 check(cwr(range(10), 4), basesize + 4 * self.ssize_t)
1894
1895 def test_permutations_sizeof(self):
1896 basesize = support.calcobjsize('4Pni')
1897 check = self.check_sizeof
1898 check(permutations('abcd'),
1899 basesize + 4 * self.ssize_t + 4 * self.ssize_t)
1900 check(permutations('abcd', 3),
1901 basesize + 4 * self.ssize_t + 3 * self.ssize_t)
1902 check(permutations('abcde', 3),
1903 basesize + 5 * self.ssize_t + 3 * self.ssize_t)
1904 check(permutations(range(10), 4),
1905 basesize + 10 * self.ssize_t + 4 * self.ssize_t)
1906
Thomas Woutersb2137042007-02-01 18:02:27 +00001907
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001908libreftest = """ Doctest for examples in the library reference: libitertools.tex
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001909
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001910
1911>>> amounts = [120.15, 764.05, 823.14]
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001912>>> for checknum, amount in zip(count(1200), amounts):
Guido van Rossum7131f842007-02-09 20:13:25 +00001913... print('Check %d is for $%.2f' % (checknum, amount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001914...
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001915Check 1200 is for $120.15
1916Check 1201 is for $764.05
1917Check 1202 is for $823.14
1918
1919>>> import operator
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001920>>> for cube in map(operator.pow, range(1,4), repeat(3)):
Guido van Rossum7131f842007-02-09 20:13:25 +00001921... print(cube)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001922...
Raymond Hettinger96ef8112003-02-01 00:10:11 +000019231
19248
192527
1926
1927>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
Raymond Hettinger3567a872003-06-28 05:44:36 +00001928>>> for name in islice(reportlines, 3, None, 2):
Guido van Rossum7131f842007-02-09 20:13:25 +00001929... print(name.title())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001930...
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001931Alex
1932Laura
1933Martin
1934Walter
1935Samuele
1936
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001937>>> from operator import itemgetter
1938>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001939>>> di = sorted(sorted(d.items()), key=itemgetter(1))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001940>>> for k, g in groupby(di, itemgetter(1)):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001941... print(k, list(map(itemgetter(0), g)))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001942...
Raymond Hettingerd25c1c62003-12-06 16:23:06 +000019431 ['a', 'c', 'e']
19442 ['b', 'd', 'f']
19453 ['g']
1946
Raymond Hettinger734fb572004-01-20 20:04:40 +00001947# Find runs of consecutive numbers using groupby. The key to the solution
1948# is differencing with a range so that consecutive numbers all appear in
1949# same group.
1950>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001951>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001952... print(list(map(operator.itemgetter(1), g)))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001953...
Raymond Hettinger734fb572004-01-20 20:04:40 +00001954[1]
1955[4, 5, 6]
1956[10]
1957[15, 16, 17, 18]
1958[22]
1959[25, 26, 27, 28]
1960
Georg Brandl3dbca812008-07-23 16:10:53 +00001961>>> def take(n, iterable):
1962... "Return first n items of the iterable as a list"
1963... return list(islice(iterable, n))
Raymond Hettingera098b332003-09-08 23:58:40 +00001964
Georg Brandl3dbca812008-07-23 16:10:53 +00001965>>> def enumerate(iterable, start=0):
1966... return zip(count(start), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001967
Georg Brandl3dbca812008-07-23 16:10:53 +00001968>>> def tabulate(function, start=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001969... "Return function(0), function(1), ..."
Georg Brandl3dbca812008-07-23 16:10:53 +00001970... return map(function, count(start))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001971
Raymond Hettingercdf8ba32009-02-19 04:45:07 +00001972>>> def nth(iterable, n, default=None):
1973... "Returns the nth item or a default value"
1974... return next(islice(iterable, n, None), default)
Raymond Hettinger60eca932003-02-09 06:40:58 +00001975
Georg Brandl3dbca812008-07-23 16:10:53 +00001976>>> def quantify(iterable, pred=bool):
1977... "Count how many times the predicate is true"
1978... return sum(map(pred, iterable))
Raymond Hettinger60eca932003-02-09 06:40:58 +00001979
Georg Brandl3dbca812008-07-23 16:10:53 +00001980>>> def padnone(iterable):
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001981... "Returns the sequence elements and then returns None indefinitely"
Georg Brandl3dbca812008-07-23 16:10:53 +00001982... return chain(iterable, repeat(None))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001983
Georg Brandl3dbca812008-07-23 16:10:53 +00001984>>> def ncycles(iterable, n):
Ezio Melotti13925002011-03-16 11:05:33 +02001985... "Returns the sequence elements n times"
Georg Brandl3dbca812008-07-23 16:10:53 +00001986... return chain(*repeat(iterable, n))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001987
1988>>> def dotproduct(vec1, vec2):
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00001989... return sum(map(operator.mul, vec1, vec2))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001990
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001991>>> def flatten(listOfLists):
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001992... return list(chain.from_iterable(listOfLists))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001993
1994>>> def repeatfunc(func, times=None, *args):
1995... "Repeat calls to func with specified arguments."
1996... " Example: repeatfunc(random.random)"
1997... if times is None:
1998... return starmap(func, repeat(args))
1999... else:
2000... return starmap(func, repeat(args, times))
2001
Raymond Hettingerd591f662003-10-26 15:34:50 +00002002>>> def pairwise(iterable):
2003... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
2004... a, b = tee(iterable)
Raymond Hettingerad983e72003-11-12 14:32:26 +00002005... try:
Georg Brandla18af4e2007-04-21 15:47:16 +00002006... next(b)
Raymond Hettingerad983e72003-11-12 14:32:26 +00002007... except StopIteration:
2008... pass
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002009... return zip(a, b)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002010
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002011>>> def grouper(n, iterable, fillvalue=None):
Raymond Hettingerf5a2e472008-07-30 07:37:37 +00002012... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002013... args = [iter(iterable)] * n
Raymond Hettinger883d2762009-01-27 04:57:51 +00002014... return zip_longest(*args, fillvalue=fillvalue)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002015
2016>>> def roundrobin(*iterables):
Raymond Hettingerf5a2e472008-07-30 07:37:37 +00002017... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002018... # Recipe credited to George Sakkis
2019... pending = len(iterables)
2020... nexts = cycle(iter(it).__next__ for it in iterables)
2021... while pending:
2022... try:
2023... for next in nexts:
2024... yield next()
2025... except StopIteration:
2026... pending -= 1
2027... nexts = cycle(islice(nexts, pending))
2028
2029>>> def powerset(iterable):
Raymond Hettingerace67332009-01-26 02:23:50 +00002030... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
2031... s = list(iterable)
2032... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002033
Raymond Hettingerad9d96b2009-01-02 21:39:07 +00002034>>> def unique_everseen(iterable, key=None):
2035... "List unique elements, preserving order. Remember all elements ever seen."
2036... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
2037... # unique_everseen('ABBCcAD', str.lower) --> A B C D
2038... seen = set()
2039... seen_add = seen.add
2040... if key is None:
2041... for element in iterable:
2042... if element not in seen:
2043... seen_add(element)
2044... yield element
2045... else:
2046... for element in iterable:
2047... k = key(element)
2048... if k not in seen:
2049... seen_add(k)
2050... yield element
2051
2052>>> def unique_justseen(iterable, key=None):
2053... "List unique elements, preserving order. Remember only the element just seen."
2054... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
2055... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
2056... return map(next, map(itemgetter(1), groupby(iterable, key)))
2057
Raymond Hettinger31b26f62014-04-02 03:16:42 -07002058>>> def first_true(iterable, default=False, pred=None):
2059... '''Returns the first true value in the iterable.
2060...
2061... If no true value is found, returns *default*
2062...
2063... If *pred* is not None, returns the first item
2064... for which pred(item) is true.
2065...
2066... '''
2067... # first_true([a,b,c], x) --> a or b or c or x
2068... # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
2069... return next(filter(pred, iterable), default)
2070
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002071This is not part of the examples but it tests to make sure the definitions
2072perform as purported.
2073
Raymond Hettingera098b332003-09-08 23:58:40 +00002074>>> take(10, count())
2075[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2076
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002077>>> list(enumerate('abc'))
2078[(0, 'a'), (1, 'b'), (2, 'c')]
2079
2080>>> list(islice(tabulate(lambda x: 2*x), 4))
2081[0, 2, 4, 6]
2082
2083>>> nth('abcde', 3)
Raymond Hettingerd04fa312009-02-04 19:45:13 +00002084'd'
2085
2086>>> nth('abcde', 9) is None
2087True
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002088
Guido van Rossum805365e2007-05-07 22:24:25 +00002089>>> quantify(range(99), lambda x: x%2==0)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000209050
2091
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002092>>> a = [[1, 2, 3], [4, 5, 6]]
2093>>> flatten(a)
2094[1, 2, 3, 4, 5, 6]
2095
2096>>> list(repeatfunc(pow, 5, 2, 3))
2097[8, 8, 8, 8, 8]
2098
2099>>> import random
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002100>>> take(5, map(int, repeatfunc(random.random)))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00002101[0, 0, 0, 0, 0]
2102
Raymond Hettingerd591f662003-10-26 15:34:50 +00002103>>> list(pairwise('abcd'))
2104[('a', 'b'), ('b', 'c'), ('c', 'd')]
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002105
Raymond Hettingerd591f662003-10-26 15:34:50 +00002106>>> list(pairwise([]))
2107[]
2108
2109>>> list(pairwise('a'))
Raymond Hettingerbefa37d2003-06-18 19:25:37 +00002110[]
2111
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002112>>> list(islice(padnone('abc'), 0, 6))
2113['a', 'b', 'c', None, None, None]
2114
2115>>> list(ncycles('abc', 3))
2116['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
2117
2118>>> dotproduct([1,2,3], [4,5,6])
211932
2120
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002121>>> list(grouper(3, 'abcdefg', 'x'))
2122[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
2123
2124>>> list(roundrobin('abc', 'd', 'ef'))
2125['a', 'd', 'e', 'b', 'f', 'c']
2126
Raymond Hettingerace67332009-01-26 02:23:50 +00002127>>> list(powerset([1,2,3]))
2128[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002129
Raymond Hettinger191e8502009-01-27 13:29:43 +00002130>>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
2131True
2132
2133>>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
2134True
2135
Raymond Hettingerad9d96b2009-01-02 21:39:07 +00002136>>> list(unique_everseen('AAAABBBCCDAABBB'))
2137['A', 'B', 'C', 'D']
2138
2139>>> list(unique_everseen('ABBCcAD', str.lower))
2140['A', 'B', 'C', 'D']
2141
2142>>> list(unique_justseen('AAAABBBCCDAABBB'))
2143['A', 'B', 'C', 'D', 'A', 'B']
2144
2145>>> list(unique_justseen('ABBCcAD', str.lower))
2146['A', 'B', 'C', 'A', 'D']
2147
Raymond Hettinger31b26f62014-04-02 03:16:42 -07002148>>> first_true('ABC0DEF1', '9', str.isdigit)
2149'0'
2150
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002151"""
2152
2153__test__ = {'libreftest' : libreftest}
2154
2155def test_main(verbose=None):
Raymond Hettingera56f6b62003-08-29 23:09:58 +00002156 test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
Thomas Woutersb2137042007-02-01 18:02:27 +00002157 RegressionTests, LengthTransparency,
Serhiy Storchaka2dae92a2013-12-09 17:45:57 +02002158 SubclassWithKwargsTest, TestExamples,
2159 SizeofTest)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002160 support.run_unittest(*test_classes)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002161
2162 # verify reference counting
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002163 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger02420702003-06-29 20:36:23 +00002164 import gc
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00002165 counts = [None] * 5
Guido van Rossum805365e2007-05-07 22:24:25 +00002166 for i in range(len(counts)):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002167 support.run_unittest(*test_classes)
Raymond Hettinger02420702003-06-29 20:36:23 +00002168 gc.collect()
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00002169 counts[i] = sys.gettotalrefcount()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002170 print(counts)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002171
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002172 # doctest the examples in the library reference
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002173 support.run_doctest(sys.modules[__name__], verbose)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00002174
Raymond Hettinger96ef8112003-02-01 00:10:11 +00002175if __name__ == "__main__":
2176 test_main(verbose=True)