From 582c7f25aaa992a3cc8618f6332d553dc5b39ada Mon Sep 17 00:00:00 2001 From: wirawan Date: Fri, 19 Feb 2010 18:41:28 +0000 Subject: [PATCH] * Generic generator module. --- generators.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 generators.py diff --git a/generators.py b/generators.py new file mode 100644 index 0000000..f5c66c5 --- /dev/null +++ b/generators.py @@ -0,0 +1,43 @@ +# -*- python -*- +# +# $Id: generators.py,v 1.1 2010-02-19 18:41:28 wirawan Exp $ +# +# Created: 20100218 +# Wirawan Purwanto +# +""" + +Various generators + +""" + +def all_combinations(seq): + """Generates stream of tuples containing all possible + combinations of items (where order matters). + + This is useful e.g. for generating all possible indices for a multidimensional + array. + Example: + >>> for i in all_combinations((xrange(4), xrange(3))): print i + (0, 0) + (1, 0) + (2, 0) + (3, 0) + (0, 1) + (1, 1) + (2, 1) + (3, 1) + (0, 2) + (1, 2) + (2, 2) + (3, 2) + + """ + if len(seq) <= 1: + for i in seq[0]: + yield (i,) + else: + for s1 in all_combinations(seq[1:]): + for s0 in seq[0]: + yield (s0,) + s1 +