Saturday, December 18, 2010

Permutations

I've recently begun working my way through ProjectEuler, and so I've had to write some code to generate permutations of lists. One way to do this is to generate all the permutations up front, in a list of lists. Below is the Python code:

def perms(l):
if len(l) == 0: return [[]]
result = []
for i in range(len(l)):
first = l[i]
rest = l[:i] + l[i+1:]
rperms = perms(rest)
rperms = [[first]+p for p in rperms]
result.append(rperms)
return result

So, for example, a call to perms([0,1,2]) yields [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]].

This works fine when your original list is small. Keep in mind, however, that the number of permutations is N! for a list of length N, so your result list will get large quickly.

When your list is too large to store all the permutations in memory at once, a slightly altered version of same algorithm can give them to you one by one via a callback function:

def perms(l,sofar,func):
if len(l) == 0:
func(sofar)
return
for i in range(len(l)):
first = l[i]
sofar.append(first)
rest = l[:i] + l[i+1:]
perms(rest,sofar,func)
sofar.pop()

This version takes 3 parameters: the first is the original list, the second is a partial result list (initially []), and the third is a function that will be called on each permutation as it is generated.

So a call to perms([0,1,2],[],func) will end up calling
func([0,1,2])
func([0,2,1])
func([1,0,2])
func([1,2,0])
func([2,0,1])
func([2,1,0])

The memory overhead for this version is O(N), since it only generates one permutation at a time.

One remaining problem with this version is that there is no way to stop early. If you are searching through all the permutations of [1,...,25] looking for one particular value, then once you find it you probably don't want to generate the other ~25! permutations. So, by changing the callback function so that it returns a boolean, we can make a version that has an early termination condition:

def perms(l,sofar,func):
if len(l) == 0:
return func(sofar)
for i in range(len(l)):
first = l[i]
sofar.append(first)
rest = l[:i] + l[i+1:]
if not(perms(rest,sofar,func)):
return False
sofar.pop()
return True


Even with the one-at-a-time version, and even with the early-out ability, one should keep in mind that a modern computer can't handle an N! computation for N bigger than around 12.

No comments:

Post a Comment