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