Permutations with generators

Paul Rubin http
Sat Jul 21 02:05:35 EDT 2007


Pablo Torres <tn.pablo at gmail.com> writes:
> def perm(seq):
> 	"Reshuffles the elements of seq in every possible way"
> 	if len(seq) == 1:
> 		yield seq
> 	else:
> 		for p in perm(seq[1:]):
> 			for i in range(len(seq)):
> 				yield p.insert(i, seq[0])

It's easiest to avoid these mutating schemes and instead just generate
each permutation separately.

def perm(seq):
   if len(seq) == 0:
       yield []
   for (i,s) in enumerate(seq):
       for p in perm(seq[:i]+seq[i+1:]):
           yield [s]+p



More information about the Python-list mailing list