Combinatorial of elements in Python?

Thomas Nelson thn at mail.utexas.edu
Wed Aug 15 11:04:03 EDT 2007


On Aug 15, 8:39 am, "Sebastian Bassi" <sba... at clubdelarazon.org>
wrote:
> That was easy :)
> What about extending it for N elements inside the dictionary? Sounds
> like a work for a recursive function.

Here's my attempt:
[code]
def backtrack(groups,position=0, answer=''):
	if position==len(groups):
		yield answer
	else:
		for e in groups[position]:
			for x in backtrack(groups,position+1,answer+e):
				yield x


groups = [
	['a','b','c'],
	['w','x','y','z'],
	['1','2']]


for i in backtrack(groups):
	print i
[/code]

If you need to put the result into a set, you can.  As for the
original question "Is there a builtin function for this", what you're
asking is essentially the standard recursive backtracking algorithm.
In your case, each "layer" in the network is fully connected to the
network below it, much the way layers in a neural network are set up.
Sadly, there isn't a graph/network algorithm module in the python
standard library.  There are graph-algorithm type libraries out there
I think, but I've never used any of them, so I can't be much help.

-Tom




More information about the Python-list mailing list