[Tutor] seed & random !?
Andrew Wilkins
toodles@yifan.net
Mon, 15 Oct 2001 19:36:33 +0800
> Indeed. Below is a function that takes a list of characters
> and returns all unique permutations thereof:
That's a funky function, Kirby!
I'm wondering if there's a better way to extend this function, so that it
returns permutations of specific numbers of elements, than what I have (by
modifying your code).
Andrew
def perm_n(set,n,t=-1):
"""
Function by Kirby Urner.
Thanks to Daniel Ajoy for sharing his Logo version with me.
Modified by Andrew Wilkins to allow specific number of elements in each
permutation.
"""
set=listify(set)
if t==-1:
if 0>n>len(set): return []
else: t=n
if n==0 or len(set)==0: return []
elif n==1: return [listify(element) for element in set]
elif len(set)==1: return set
answ = []
for i in range(len(set)):
base = [set[0]]
rest = set[1:]
if t>1: answ = answ + [base + listify(i) for i in
perm_n(rest,n,t-1)]
else: answ = answ + [base]
set = [set[-1]]+set[:-1]
return answ
def listify(obj):
"Just so I can use tuples...eg. perm_n(range(10))."
if type(obj) is not type([]):
try:
l=list(obj)
except: l=[obj]
return l
else: return obj
>
>
> 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
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>