Pattern for permutations?

Christophe Delord christophe.delord at free.fr
Thu Apr 11 05:09:22 EDT 2002


Hello,

I have a simple solution using generators (python 2.2).
(think recursive!)


from __future__ import generators

def prod(*seqs):
	if seqs:
		for x in seqs[0]:
			for xs in prod(*seqs[1:]):
				yield (x,)+xs
	else:
		yield ()

for x,y,z in prod((1,2,3),('a','b','c'),(4,5,6)):
	print x,y,z



Hope it helps!

Christophe.


Tim Churches wrote:

> This may be an elementary question but the solution is
> not obvious to me.
> 
> I want to define a function which takes as its argument a
> list which contains one or more sequences, and then does stuff
> with every permutation of the elements of those sequences. For
> example, a function which works for a list containing three
> sequences:
> 
> def nestedloops(list_of_sequences):
> 	for element0 in list_of_sequences[0]:
> 		for element1 in list_of_sequences[1]:
> 			for element2 in list_of_sequences[2]:
> 				# do stuff with each permutation
> 				print element0, element1, element2
> 
> nestedloops([(1,2,3),('one','two','three'),('isa','dalawa','tatlo')])
> 
> How does one generalise such a function so that it handles any number 
> of sequences in the passed list of sequences i.e. a dynamic number of
> levels of nesting? 
> 
> It occurred to me that the function could emit dynamic code for the 
> "for" loops and then eval() that, but that seems a bit messy and
> possibly slow.
> 
> Is there a better way?
> 
> Tim C
> 
> 
> 


-- 
Christophe Delord
http://christophe.delord.free.fr/




More information about the Python-list mailing list