473,788 Members | 2,854 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
10 5677
hu********@yaho o.com (Hung Jung Lu) wrote:
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. :)


Well, here they are: (for functional people, basically I used
tail-call and parameter list to emulate looping variables... standard
trick, nothing new. The formulas might be further simplified?)

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

combinations = lambda Xs, k: [p[0] for p in reduce(lambda r, i:
[[x+[y[i]], y[i+1:]] for (x, y) in r for i in range(len(y))],
range(k), [[[], Xs]])]

slot_machine_co mbinations = lambda Xs, k: [p[0] for p in reduce(lambda
r, i: [[x+[y[i]], y] for (x, y) in r for i in range(len(y))],
range(k), [[[], Xs]])]

sample = ['a', 'b', 'c', 'd']
print permutations(sa mple, 2)
print combinations(sa mple, 2)
print slot_machine_co mbinations(samp le, 2)

The three formulas only differ in the treatment of the y[] lists in
looping. That part can be parametrized into separate lambdas if so
desired.

permutations: y --> y[:i] + y[i+1:]
combinations: y --> y[i+1:]
slot_machine_co mbinations: y --> y

Hung Jung
Jul 18 '05 #11

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

Similar topics

1
4232
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
2891
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
2433
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
16845
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
8099
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
4245
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
2343
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
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
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,...
0
10364
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
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
8993
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...
0
5398
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...
1
4069
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
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.