MCPcopy Index your code
hub / github.com/python/cpython / test_combinations

Method test_combinations

Lib/test/test_itertools.py:225–282  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

223 self.assertEqual(list(islice(chain.from_iterable(repeat(range(5))), 2)), [0, 1])
224
225 def test_combinations(self):
226 self.assertRaises(TypeError, combinations, 'abc') # missing r argument
227 self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
228 self.assertRaises(TypeError, combinations, None) # pool is not iterable
229 self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
230
231 def combinations1(iterable, r):
232 'Pure python version shown in the docs'
233 pool = tuple(iterable)
234 n = len(pool)
235 if r > n:
236 return
237 indices = list(range(r))
238 yield tuple(pool[i] for i in indices)
239 while 1:
240 for i in reversed(range(r)):
241 if indices[i] != i + n - r:
242 break
243 else:
244 return
245 indices[i] += 1
246 for j in range(i+1, r):
247 indices[j] = indices[j-1] + 1
248 yield tuple(pool[i] for i in indices)
249
250 def combinations2(iterable, r):
251 'Pure python version shown in the docs'
252 pool = tuple(iterable)
253 n = len(pool)
254 for indices in permutations(range(n), r):
255 if sorted(indices) == list(indices):
256 yield tuple(pool[i] for i in indices)
257
258 def combinations3(iterable, r):
259 'Pure python version from cwr()'
260 pool = tuple(iterable)
261 n = len(pool)
262 for indices in combinations_with_replacement(range(n), r):
263 if len(set(indices)) == r:
264 yield tuple(pool[i] for i in indices)
265
266 for n in range(7):
267 values = [5*x-12 for x in range(n)]
268 for r in range(n+2):
269 result = list(combinations(values, r))
270 self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs
271 self.assertEqual(len(result), len(set(result))) # no repeats
272 self.assertEqual(result, sorted(result)) # lexicographic order
273 for c in result:
274 self.assertEqual(len(c), r) # r-length combinations
275 self.assertEqual(len(set(c)), r) # no duplicate elements
276 self.assertEqual(list(c), sorted(c)) # keep original ordering
277 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
278 self.assertEqual(list(c),
279 [e for e in values if e in c]) # comb is a subsequence of the input iterable
280 self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
281 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
282 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version

Callers

nothing calls this directly

Calls 6

listClass · 0.85
factFunction · 0.85
setFunction · 0.85
assertTrueMethod · 0.80
assertRaisesMethod · 0.45
assertEqualMethod · 0.45

Tested by

no test coverage detected