[Tutor] seed & random !?

Kirby Urner urnerk@qwest.net
Sun, 14 Oct 2001 17:37:35 -0700


At 06:55 AM 10/14/2001 -0400, Andrei Kulakov wrote:

>But.. do you need *all* permutations? If so, there must be a more
>efficient and straightforward way to do this..

Indeed.  Below is a function that takes a list of characters
and returns all unique permutations thereof:


def perm(set):
     """
     Return all permutations of a set.  Thanks to
     Daniel Ajoy for sharing his Logo version with me.
     """

     if len(set)==0:  return []
     if len(set)==1:  return set

     answ = []

     for i in range(len(set)):
         base = [set[0]]
         rest = set[1:]
         answ = answ + [base + list(i) for i in perm(rest)]
         set = [set[-1]]+set[:-1]

     return answ

   >>> perm(['1','2','3'])
   [['1', '2', '3'], ['1', '3', '2'], ['3', '1', '2'],
   ['3', '2', '1'], ['2', '3', '1'], ['2', '1', '3']]

   >>> perm(['1','2','3','4'])
   [['1', '2', '3', '4'], ['1', '2', '4', '3'],
   ['1', '4', '2', '3'], ['1', '4', '3', '2'],
   ['1', '3', '4', '2'], ['1', '3', '2', '4'],
   ['4', '1', '2', '3'], ['4', '1', '3', '2'],
   ['4', '3', '1', '2'], ['4', '3', '2', '1'],
   ['4', '2', '3', '1'], ['4', '2', '1', '3'],
   ['3', '4', '1', '2'], ['3', '4', '2', '1'],
   ['3', '2', '4', '1'], ['3', '2', '1', '4'],
   ['3', '1', '2', '4'], ['3', '1', '4', '2'],
   ['2', '3', '4', '1'], ['2', '3', '1', '4'],
   ['2', '1', '3', '4'], ['2', '1', '4', '3'],
   ['2', '4', '1', '3'], ['2', '4', '3', '1']]

I use it in my simplematrix module as part of what's needed
to get the determinant of a matrix.

Nothing random about it though.

Kirby