MCPcopy Index your code
hub / github.com/RustPython/RustPython / test_product

Method test_product

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

Source from the content-addressed store, hash-verified

988 check(4, [(([2], [3]), [4])])
989
990 def test_product(self):
991 for args, result in [
992 ([], [()]), # zero iterables
993 (['ab'], [('a',), ('b',)]), # one iterable
994 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
995 ([range(0), range(2), range(3)], []), # first iterable with zero length
996 ([range(2), range(0), range(3)], []), # middle iterable with zero length
997 ([range(2), range(3), range(0)], []), # last iterable with zero length
998 ]:
999 self.assertEqual(list(product(*args)), result)
1000 for r in range(4):
1001 self.assertEqual(list(product(*(args*r))),
1002 list(product(*args, **dict(repeat=r))))
1003 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
1004 self.assertRaises(TypeError, product, range(6), None)
1005
1006 def product1(*args, **kwds):
1007 pools = list(map(tuple, args)) * kwds.get('repeat', 1)
1008 n = len(pools)
1009 if n == 0:
1010 yield ()
1011 return
1012 if any(len(pool) == 0 for pool in pools):
1013 return
1014 indices = [0] * n
1015 yield tuple(pool[i] for pool, i in zip(pools, indices))
1016 while 1:
1017 for i in reversed(range(n)): # right to left
1018 if indices[i] == len(pools[i]) - 1:
1019 continue
1020 indices[i] += 1
1021 for j in range(i+1, n):
1022 indices[j] = 0
1023 yield tuple(pool[i] for pool, i in zip(pools, indices))
1024 break
1025 else:
1026 return
1027
1028 def product2(*iterables, repeat=1):
1029 'Pure python version used in docs'
1030 if repeat < 0:
1031 raise ValueError('repeat argument cannot be negative')
1032 pools = [tuple(pool) for pool in iterables] * repeat
1033
1034 result = [[]]
1035 for pool in pools:
1036 result = [x+[y] for x in result for y in pool]
1037
1038 for prod in result:
1039 yield tuple(prod)
1040
1041 argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3),
1042 set('abcdefg'), range(11), tuple(range(13))]
1043 for i in range(100):
1044 args = [random.choice(argtypes) for j in range(random.randrange(5))]
1045 expected_len = prod(map(len, args))
1046 self.assertEqual(len(list(product(*args))), expected_len)
1047 self.assertEqual(list(product(*args)), list(product1(*args)))

Callers

nothing calls this directly

Calls 8

listClass · 0.85
lenFunction · 0.85
setFunction · 0.85
choiceMethod · 0.80
randrangeMethod · 0.80
prodFunction · 0.70
assertEqualMethod · 0.45
assertRaisesMethod · 0.45

Tested by

no test coverage detected