@@ -455,7 +455,7 @@ loops that truncate the stream.
455455 def product(*args, repeat=1):
456456 # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
457457 # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
458- pools = map( tuple, args) * repeat
458+ pools = [ tuple(pool) for pool in args] * repeat
459459 result = [[]]
460460 for pool in pools:
461461 result = [x+[y] for x in result for y in pool]
@@ -617,7 +617,8 @@ which incur interpreter overhead.
617617 return sum(map(operator.mul, vec1, vec2))
618618
619619 def flatten(listOfLists):
620- return list(chain.from_iterable(listOfLists))
620+ "Flatten one level of nesting"
621+ return chain.from_iterable(listOfLists)
621622
622623 def repeatfunc(func, times=None, *args):
623624 """Repeat calls to func with specified arguments.
@@ -703,6 +704,27 @@ which incur interpreter overhead.
703704 except exception:
704705 pass
705706
707+ def random_product(*args, repeat=1):
708+ "Random selection from itertools.product(*args, **kwds)"
709+ pools = [tuple(pool) for pool in args] * repeat
710+ return [random.choice(pool) for pool in pools]
711+
712+ def random_permuation(iterable, r=None):
713+ "Random selection from itertools.permutations(iterable, r)"
714+ pool = tuple(iterable)
715+ r = len(pool) if r is None else r
716+ return random.sample(pool, r)
717+
718+ def random_combination(iterable, r):
719+ "Random selection from itertools.combinations(iterable, r)"
720+ pool = tuple(iterable)
721+ return sorted(random.sample(pool, r), key=pool.index)
722+
723+ def random_combination_with_replacement(iterable, r):
724+ "Random selection from itertools.combinations_with_replacement(iterable, r)"
725+ pool = tuple(iterable)
726+ return sorted(map(random.choice, repeat(pool, r)), key=pool.index)
727+
706728Note, many of the above recipes can be optimized by replacing global lookups
707729with local variables defined as default values. For example, the
708730*dotproduct * recipe can be written as::
0 commit comments