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

Method test_product

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

Source from the content-addressed store, hash-verified

1040 check(4, [(([2], [3]), [4])])
1041
1042 def test_product(self):
1043 for args, result in [
1044 ([], [()]), # zero iterables
1045 (['ab'], [('a',), ('b',)]), # one iterable
1046 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
1047 ([range(0), range(2), range(3)], []), # first iterable with zero length
1048 ([range(2), range(0), range(3)], []), # middle iterable with zero length
1049 ([range(2), range(3), range(0)], []), # last iterable with zero length
1050 ]:
1051 self.assertEqual(list(product(*args)), result)
1052 for r in range(4):
1053 self.assertEqual(list(product(*(args*r))),
1054 list(product(*args, **dict(repeat=r))))
1055 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
1056 self.assertRaises(TypeError, product, range(6), None)
1057
1058 def product1(*args, **kwds):
1059 pools = list(map(tuple, args)) * kwds.get('repeat', 1)
1060 n = len(pools)
1061 if n == 0:
1062 yield ()
1063 return
1064 if any(len(pool) == 0 for pool in pools):
1065 return
1066 indices = [0] * n
1067 yield tuple(pool[i] for pool, i in zip(pools, indices))
1068 while 1:
1069 for i in reversed(range(n)): # right to left
1070 if indices[i] == len(pools[i]) - 1:
1071 continue
1072 indices[i] += 1
1073 for j in range(i+1, n):
1074 indices[j] = 0
1075 yield tuple(pool[i] for pool, i in zip(pools, indices))
1076 break
1077 else:
1078 return
1079
1080 def product2(*iterables, repeat=1):
1081 'Pure python version used in docs'
1082 if repeat < 0:
1083 raise ValueError('repeat argument cannot be negative')
1084 pools = [tuple(pool) for pool in iterables] * repeat
1085
1086 result = [[]]
1087 for pool in pools:
1088 result = [x+[y] for x in result for y in pool]
1089
1090 for prod in result:
1091 yield tuple(prod)
1092
1093 argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3),
1094 set('abcdefg'), range(11), tuple(range(13))]
1095 for i in range(100):
1096 args = [random.choice(argtypes) for j in range(random.randrange(5))]
1097 expected_len = prod(map(len, args))
1098 self.assertEqual(len(list(product(*args))), expected_len)
1099 self.assertEqual(list(product(*args)), list(product1(*args)))

Callers

nothing calls this directly

Calls 7

listClass · 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