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