473,773 Members | 2,334 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Recursive function to develop permutations

Hi,

I am trying to come up with a way to develop all n-length permutations of a
given list of values. The short function below seems to work, but I can't
help thinking there's a better way. Not being a computer scientist, I find
recursive functions to be frightening and unnatural. I'd appreciate if
anyone can tell me the pythonic idiom to accomplish this.

Thanks for your help,

Steve Goldman

###START CODE###

def permute(list,n, initialize=True ):
"""A recursive function that returns a list of all length n ordered
permutations of "list", length k."""
if initialize:
global permutation, permutation_lis t
permutation=[] #This list holds the individual permutations. It
is built one element at a time
permutation_lis t=[] #This list is the list that will contain all
the permutations
n=n-1 #This counts down for each element of the permutation. It is a
local variable,
#so each subsequent function call has n reduced by one
for e in list:
permutation.app end(e)
if n>0: #that is,the permutation needs additional elements
permute(list,n, False)
else: # the permutation is length n
permutation_lis t.append(permut ation[:]) #store the completed
permutation
permutation.pop (-1) # knock off the last value and go to the next
element in "list"
return permutation_lis t
if __name__=='__ma in__':
list=['red','white',' blue','green']
print permute(list,3)

Jul 18 '05 #1
10 5675
Hello Steve,
I am trying to come up with a way to develop all n-length permutations of a
given list of values.
###START CODE###
...

Side note:
Please make sure that when posting to a newgroup your lines are less than
78 charcters long.

I'd split the problem (If I understand it correctly) to two problems:
1. Find all sublist of size n of l
2. Find all permutations of a list l

And using generators is always fun :-)

Something in the lines of:
#!/usr/bin/env python

def sublists(l, n):
'''All sublists in length 'n' of 'l' '''
assert(len(l) >= n)

if len(l) == n: # Recursion base
yield l
return

for i in range(len(l)): # Remove one item and recurse
for sub in sublists(l[:i] + l[i+1:], n):
yield sub

def permutations(l) :
'''All permuatations of 'l' '''
if len(l) == 1: # Rercursion base
yield l
return

for i, v in enumerate(l):
for p in permutations(l[:i] + l[i+1:]):
yield [v] + p

def subperm(l, n):
'''All permutation of sublists in size 'n' of 'l' '''
for s in sublists(l, n):
for p in permutations(s) :
yield p

if __name__ == "__main__":
from sys import argv

l = range(int(argv[1]))
n = int(argv[2])

for p in subperm(l, n):
print p

HTH.
--
------------------------------------------------------------------------
Miki Tebeka <mi*********@gm ail.com>
http://tebeka.spymac.net
The only difference between children and adults is the price of the toys
Jul 18 '05 #2
On Tue, Oct 19, 2004 at 12:34:57AM +0000, Steve Goldman wrote:
Hi,

I am trying to come up with a way to develop all n-length permutations of a
given list of values. The short function below seems to work, but I can't
help thinking there's a better way. Not being a computer scientist, I find
recursive functions to be frightening and unnatural. I'd appreciate if
anyone can tell me the pythonic idiom to accomplish this.

###START CODE###

[snip]

Combinatorics (permutations, combinations, etc) get golfed (shortest/fastest)
on c.l.py a couple times a year. Check groups.google.c om for some solutions.
If you want fast, try probstat.sf.net which does some combinatorics in C with
a python wrapper. disclosure: I wrote it.

-Jack
Jul 18 '05 #3
Steve Goldman <st*****@ix.net com.com> wrote:
Hi,

I am trying to come up with a way to develop all n-length permutations of a
given list of values. The short function below seems to work, but I can't
help thinking there's a better way. Not being a computer scientist, I find
recursive functions to be frightening and unnatural. I'd appreciate if
anyone can tell me the pythonic idiom to accomplish this.


The implementation of something that is naturally defined recursively is
often simplest when done recursively (unless there's some manual
equivalent of a "tail call optimization" that's easy and natural). And
many things in combinatorics are generally subject to naturally
recursive definitions.

If you hope to find a natural and smooth non-recursive implementation,
think first about a non-recursive definition (the alternative is putting
the recursion in, then removing it by explicitly introducing a stack; it
works, but is not necessarily pretty).

In this case it seems to me that you're lucky: there IS a non-recursive
definition of "permutatio ns of length N out of a list of X values". It
may go something like...:
each result is a container with N slots. each slot, independently,
assumes each of the X values, yielding X**N results

This is like saying that (if the X values are digits in base X) the
result is a number counting in base X from 0 to X**N-1. In fact, the X
values may be arbitrary, but the INDICES of the values in the list that
holds them ARE the numbers 0 to X-1, i.e., exactly the digits in base X.

So, we have reduced the problem to one of counting in an arbitrary base,
so it becomes pretty easy to solve non-recursively. For example:

def permute(Xs, N):
permutations = []
permutation = [None] * N
X = len(Xs)
for i in xrange(X**N):
for j in xrange(N):
i, k = divmod(i, X)
permutation[j] = Xs[k]
permutations.ap pend(list(permu tation))
return permutations

Here, we're using i as an actual count, an integer, and the inner loop
does the 'base expansion' of each i, plus the indexing to replace each
digit with the corresponding item of Xs.

Note that I've called the argument Xs, *NOT* list, because I want to use
the built-in name 'list' for its normal purpose: making a new list
that's a copy of an existing one (I prefer that to such goofy idioms as
permutation[:], permutation+[], or permutation*1, even though they all
do the same job and the last one is a real characters-saver; I think
list(permutatio n) is more readable, personally).

In general, it's best to avoid shadowing built-in names in a context
where you're likely to want to use the original meaning of the names.

Of course, there ARE other ways to count:

def permute(Xs, N):
permutations = []
permutation = [0] * N
X = len(Xs)
while True:
for k in xrange(N):
permutation[k] += 1
if permutation[k] < X: break
permutation[k] = 0
else:
break
permutations.ap pend([Xs[k] for k in permutation])
return permutations

Here, I need to use a list comprehension (or some slightly more obscure
construct, such as map(Xs.__getite m__, permutation)... ) at append time,
to construct the list of items of Xs from the list of indexes ("digits")
which the algorithm naturally generates. I hold digits in a
little-endian way, btw, simply because it's marginally simpler and you
did not specify any particular ordering for the result.

Each of these solutions can be enhanced by making it into a generator --
remove the permutations=[] at the start, turn the permutations.ap pend
call into a yield statement. However, you'll have to turn the simple
"print permute(..." into a "print list(permute(.. ." in your testcase.
No big deal, if you do need a list as a result; it's frequent that what
you want is to LOOP over the result, in which case there's no need to
make it into a list taking memory space all at once.

Are these "counting" solutions any simpler than the recursive one? I
don't really think so, for a cleanly-implemented recursion (one without
globals and a first-time switch...!-) such as:

def permute(Xs, N):
if N <= 0:
yield []
return
for x in Xs:
for sub in permute(Xs, N-1):
yield [x]+sub

it seems to me this one has a strong simplicity advantage. However,
considering the "counting" approaches is still instructive. Take the
second one again: all the counting it does is a += 1 and a check if some
limit is reached that way. But that's VERY close to the job of an
iterator, so why not try to use an iterator directly instead of that
"digit in base X"/"index into Xs" number...? Python generally prefers
iterating directly over values, rather than over digits...

def permute(Xs, N):
state = [iter(Xs) for k in xrange(N)]
permutation = [s.next() for s in state]
while True:
yield list(permutatio n)
for k in xrange(N):
try: permutation[k] = state[k].next()
except StopIteration:
state[k] = iter(Xs)
permutation[k] = state[k].next()
else:
break
else:
break

A bit cutesy, perhaps, particularly with the two "else: break" back to
back (one for the try statement breaking out of the for, one for the for
statement breaking out of the while).

And so on, and so forth. There's hardly any limit to the fun one can
have exploring such problems.

But, for simplicity, recursion is still hard to beat;-).
Alex
Jul 18 '05 #4
Thanks to everyone for lots to think about. I really like the concept of
counting in base "X" as a model for this problem.

But now I have another question. In the elegant recursive generator, below,
the yield expression for the terminating condition is followed by a return
statement. Why is that necessary? I know it is, because I tried taking it
out with unhappy consequences. I thought yield had the same effect as
return, except that the function's state was "frozen" until the next
iteration.

Thanks again.
Are these "counting" solutions any simpler than the recursive one? I
don't really think so, for a cleanly-implemented recursion (one without
globals and a first-time switch...!-) such as:

def permute(Xs, N):
if N <= 0:
yield []
return
for x in Xs:
for sub in permute(Xs, N-1):
yield [x]+sub


Jul 18 '05 #5
Steve Goldman <steve_g <at> ix.netcom.com> writes:
But now I have another question. In the elegant recursive generator, below,
the yield expression for the terminating condition is followed by a return
statement. Why is that necessary?

[snip]
def permute(Xs, N):
if N <= 0:
yield []
return
for x in Xs:
for sub in permute(Xs, N-1):
yield [x]+sub
The 'return' statement tells the generator to exit the function (without
saving the state. So,
def gen(): .... yield 1
.... return
.... yield 2
.... list(gen())

[1]

Note that the second yield is never reached. So the source of your example
above chose to use the 'return' statement instead of the perhaps more
intuitive (but slightly more indented):

def permute(Xs, N):
if N <= 0:
yield []
else:
for x in Xs:
for sub in permute(Xs, N-1):
yield [x]+sub

Steve

Jul 18 '05 #6
Steve Goldman <st*****@ix.net com.com> wrote:
Thanks to everyone for lots to think about. I really like the concept of
counting in base "X" as a model for this problem.
You're welcome.
But now I have another question. In the elegant recursive generator, below,
the yield expression for the terminating condition is followed by a return
statement. Why is that necessary? I know it is, because I tried taking it
It's not; a
raise StopIteration
or putting the rest of the program in an 'else:' would be just as good.
out with unhappy consequences. I thought yield had the same effect as
return, except that the function's state was "frozen" until the next
iteration.


You need to terminate the recursion sooner or later. To do that, you
must get a StopIteration exception raised. That happens with the
appropriate raise statement, or a return, or "falling off the end of the
code", which is equivalent to a return.

I generally prefer return, as it's concise and avoids extra nesting.
But if you'd rather do if/else, you can code, for example:

def permute(Xs, N):
if N > 0:
for x in Xs:
for sub in permute(Xs, N-1):
yield [x]+sub
else:
yield []

If you do choose an if/else it seems to me things are more readable when
you arrange them this way (rather than with if N<=0, so the for in the
else). Matter of tastes, of course.
Alex
Jul 18 '05 #7
al*****@yahoo.c om (Alex Martelli) wrote:

def permute(Xs, N):
if N > 0:
for x in Xs:
for sub in permute(Xs, N-1):
yield [x]+sub
else:
yield []

If you do choose an if/else it seems to me things are more readable when
you arrange them this way (rather than with if N<=0, so the for in the
else). Matter of tastes, of course.


For an unreadable voodoo version, here is a one-liner:

permute = lambda Xs, N: reduce(lambda r, a: [p + [x] for p in r for x
in Xs], range(N), [[]])

print permute(['red', 'white', 'blue', 'green'], 3)

Actually, we should probably not call it "permute". In combinatorics,
"permutatio n" usually is reserved for sorting operation on a given
combination. However, I don't have a good name for the described
operation, either. Some people would probably call it "sequential draw
with replacement". It's more like "combinatio n" as in the case of a
"combinatio n lock", or as in "slot-machine combinations". (46 entries
in Google. Zero entry for "slot-machine permutations", quoted search
used.)

For simple permutation on a given list, the voodoo version is:

permutations = lambda x: reduce(lambda r, a: [p[:i] + [a] + p[i:] for
p in r for i in range(len(p)+1)], x[1:], [x[:1]])

print permutations(['a', 'b', 'c'])

No if/else statements. No explicit recursion. And it works for
zero-length lists as well. Now, if someone could do the general P(n,
k) and C(n, k) versions, I'd appreciate it. :)

Hung Jung
Jul 18 '05 #8
* Steve Goldman (2004-10-19 02:34 +0200)
I am trying to come up with a way to develop all n-length permutations of a
given list of values.


I'm sorry but there are no "n-length permutations" in
mathematics/combinatorics. There are variations and combinations -
each of them with and without repetition. The difference is that with
combinations order of the elements is irrelevant and with variations
order is relevant.

Permutations always have the full length of the original list.
Permutations are divided in permutations with and without repetition
(like combinations and variations).

For an (unoptimized) version of permutations see:
http://www.python.org/doc/current/ref/indentation.html
Thorsten

PS If you are interested I can post the code for all six
possibilities. The code computes optionally the size of the result
list (because this grows big very soon) so you don't run out of memory
or time
Jul 18 '05 #9
* Hung Jung Lu (2004-10-22 07:09 +0200)
Actually, we should probably not call it "permute". In combinatorics,
"permutatio n" usually is reserved for sorting operation on a given
combination.


Not at all. Permutations and combinations have nothing in common. And
permutations aren't "sorted".
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4231
by: SimonVC | last post by:
Is there a way to do this as a list comprehension? >>> def recu(alist, blist=): .... if len(alist)==0: print blist .... for i in range(len(alist)): .... blist.append(alist.pop(i)) .... recu(alist, blist) .... alist.insert(i, blist.pop()) >>> recu(list("abc"))
2
2889
by: | last post by:
OK: Purpose: Using user's input and 3 recursive functions, construct an hour glass figure. Main can only have user input, loops and function calls. Recursive function 1 takes input and displays a sequence of spaces; recursive function 2 uses input to display ascending sequence of digits; likewise, recursive function 3 uses input to display descending sequence of digits. I have not followed the instructions completely regarding the...
4
2431
by: Nicolas Vigier | last post by:
Hello, I have in my python script a function that look like this : def my_function(arg1, arg2, opt1=0, opt2=1, opt3=42): if type(arg1) is ListType: for a in arg1: my_function(a, arg2, opt1=opt1, opt2=opt2, opt3=opt3) return if type(arg2) is ListType:
4
9055
by: Victor | last post by:
Hello, I've got a situation in which the number of (valid) recursive calls I make will cause stack overflow. I can use getrlimit (and setrlimit) to test (and set) my current stack size. However, it is not as straightforward to determine the base address for my stack space. The approach I have taken is to save the address of an automatic variable in main( ), and assume this is a fairly good indicator of my base address. Then, I can...
2
1418
by: Paulo Eduardo | last post by:
Hi, all We are using Microsoft Visual C++ 6.0 Service Pack 6. We need to develop a recursive function to search files in fix drives of user machine. Is there one API that implement recursity in it? Will we need to develop recursive function using FindFirstFile and FindNextFile? Thanks in advance.
9
16844
by: Csaba Gabor | last post by:
Inside a function, I'd like to know the call stack. By this I mean that I'd like to know the function that called this one, that one's caller and so on. So I thought to do: <script type='text/javascript'> function myFunc(lev) { // if (lev) return myFunc(lev-1); var aStack=; nextFunc = arguments.callee;
17
8098
by: DanielJohnson | last post by:
how to use the combination function in python ? For example 9 choose 2 (written as 9C2) = 9!/7!*2!=36 Please help, I couldnt find the function through help.
3
4243
by: from.future.import | last post by:
Hi, I encountered garbage collection behaviour that I didn't expect when using a recursive function inside another function: the definition of the inner function seems to contain a circular reference, which means it is only collected by the mark-and-sweep collector, not by reference counting. Here is some code that demonstrates it: === def outer():
3
2342
by: Davy | last post by:
Hi all, Sometimes I need to pass same parameter in recursive function. From my point of view, the style is redundant, and I don't what to use some global style like self.A, self.B, Is there any other choice? For example, def func(self, x, y, A, B, C): #x, y change in recursive call
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.