473,804 Members | 3,021 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unyeilding a permutation generator

Hello, can someone please help.

I found the following code at http://code.activestate.com/recipes/252178/

def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm) +1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]

which allows me to do things like

for x in all_permx("ABCD "):
print x

I believe it is making use of the plain changes / Johnson Trotter
algorithm.
Can someone please confirm?

Anyway what I want to do is experiment with code similar to this (i.e.
same algorithm and keep the recursion) in other languages,
particularly vbscript and wondered what it would look like if it was
rewritten to NOT use the yield statement - or at least if it was
amended so that it can be easily translated to other languages that
dont have python's yield statement. I think the statement "for perm in
all_perms(str[1:]):" will be hardest to replicate in a recursive
vbscript program for example.

Thanks for any constructive help given.

Hal
Nov 2 '08 #1
13 2247
si******@yahoo. com writes:
Anyway what I want to do is experiment with code similar to this (i.e.
same algorithm and keep the recursion) in other languages,
particularly vbscript and wondered what it would look like if it was
rewritten to NOT use the yield statement -
Without the yield statement and keeping the same space complexity, you
basically have to wrap the enumeration state in a data object that you
can enumerate over explicitly. That in turn may mean you have to
unwind the recursion into old fashioned stack operations.
Nov 2 '08 #2
si******@yahoo. com wrote:
Anyway what I want to do is experiment with code similar to this (i.e.
same algorithm and keep the recursion) in other languages,
particularly vbscript and wondered what it would look like if it was
rewritten to NOT use the yield statement
An obvious (though memory-inefficient) replacement is to accumulate a
list and return the list. Initialize a result variable to an empty list,
and instead of yielding elements, append them to the result variable.
Then return the result variable at the end of the function.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
Nov 2 '08 #3
On Nov 2, 3:34*pm, silly...@yahoo. com wrote:
Hello, can someone please help.

I found the following code athttp://code.activestat e.com/recipes/252178/

def all_perms(str):
* * if len(str) <=1:
* * * * yield str
* * else:
* * * * for perm in all_perms(str[1:]):
* * * * * * for i in range(len(perm) +1):
* * * * * * * * #nb str[0:1] works in both string and list contexts
* * * * * * * * yield perm[:i] + str[0:1] + perm[i:]

which allows me to do things like

for x in *all_permx("ABC D"):
* print x

I believe it is making use of the plain changes / Johnson Trotter
algorithm.
Can someone please confirm?

Anyway what I want to do is experiment with code similar to this (i.e.
same algorithm and keep the recursion) in other languages,
particularly vbscript and wondered what it would look like if it was
rewritten to NOT use the yield statement - or at least if it was
amended so that it can be easily translated to other languages that
dont have python's yield statement. I think the statement "for perm in
all_perms(str[1:]):" *will be hardest to replicate in a recursive
vbscript program for example.

Thanks for any constructive help given.

Hal
I think multi-threading is the "truest" to the original. You might
develop a framework to set events when particular generators are to
take a turn, place their "yields", per se, in a particular place, set
the return event, etc., and reuse it. Of course, starting threads in
VBS might be another matter.
Nov 2 '08 #4
si******@yahoo. com wrote:
Hello, can someone please help.

I found the following code at http://code.activestate.com/recipes/252178/

def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm) +1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]

which allows me to do things like

for x in all_permx("ABCD "):
print x

I believe it is making use of the plain changes / Johnson Trotter
algorithm.
Can someone please confirm?

Anyway what I want to do is experiment with code similar to this (i.e.
same algorithm and keep the recursion) in other languages,
particularly vbscript and wondered what it would look like if it was
rewritten to NOT use the yield statement - or at least if it was
amended so that it can be easily translated to other languages that
dont have python's yield statement. I think the statement "for perm in
all_perms(str[1:]):" will be hardest to replicate in a recursive
vbscript program for example.
There are various approaches you could use, the simplest of which is to
provide a "callback function" as an additional argument to the all_perms
function, and call it with the permutation as an argument in place of
the yield statement.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Nov 3 '08 #5
Steve Holden wrote:
si******@yahoo. com wrote:
>Anyway what I want to do is experiment with code similar to this (i.e.
same algorithm and keep the recursion) in other languages,
particularly vbscript and wondered what it would look like if it was
rewritten to NOT use the yield statement - or at least if it was
amended so that it can be easily translated to other languages that
dont have python's yield statement. I think the statement "for perm in
all_perms(st r[1:]):" will be hardest to replicate in a recursive
vbscript program for example.
There are various approaches you could use, the simplest of which is to
provide a "callback function" as an additional argument to the all_perms
function, and call it with the permutation as an argument in place of
the yield statement.
I had thought of three ways to avoid yield, that makes a fourth.

Summary:

1. Think of generator function as an abbreviated iterator class and
unabbreviate by writing a full iterator class with .__next__ (3.0).
+ Transparent to caller
- Will often have to re-arrange code a bit to save locals values as
attributes before returning. If there is an inner loop, efficiency may
require copying attributes to locals.

2. Add to collection rather than yield, then return collection rather
than raise StopIteration.
+ Transparent to caller; small change to function.
- Returned collection can be arbitrarily large and take an arbitrarily
long time to collect.

3. Add callback parameter and change 'yield value' to 'callback(value )'.
+ Minor change to generator function.
- Minor to major change to caller to turn consumer code into a callback
that somehow gets result of callback to where it is needed. (Avoiding
the major changes sometimes needed was one of the motivations for
generators.)

4. Combine caller and generator code by inlining one into or around the
other.
+ Neither code will change much.
- Loss benefit of modularity and reuse without cut-and-paste, which is
subject to error.

I have not thought through yet how well each of these work with
recursive generators.

Conclusion:

Generators with yield make Python a great language for expressing
combinatorial algorithms.

Terry Jan Reedy

Nov 3 '08 #6
On Nov 2, 10:34*pm, silly...@yahoo. com wrote:
Anyway what I want to do is experiment with code similar to this (i.e.
same algorithm and keep the recursion) in other languages,
particularly vbscript and wondered what it would look like if it was
rewritten to NOT use the yield statement - or at least if it was
amended so that it can be easily translated to other languages that
dont have python's yield statement. I think the statement "for perm in
all_perms(str[1:]):" *will be hardest to replicate in a recursive
vbscript program for example.

Thanks for any constructive help given.
Here is a solution which does not use yield, translittered
from some Scheme code I have:

def perm(lst):
ll = len(lst)
if ll == 0:
return []
elif ll == 1:
return [lst]
else:
return [[el] + ls for el in lst
for ls in perm([e for e in lst if not e==el])]

if __name__ == '__main__':
print perm('abcd')
Nov 3 '08 #7
On Sun, 2 Nov 2008 14:09:01 -0800 (PST), Aaron Brady <ca********@gma il.comwrote:
On Nov 2, 3:34*pm, silly...@yahoo. com wrote:
....
>for x in *all_permx("ABC D"):
* print x
....
I think multi-threading is the "truest" to the original. You might
develop a framework to set events when particular generators are to
take a turn, place their "yields", per se, in a particular place, set
the return event, etc., and reuse it. Of course, starting threads in
VBS might be another matter.
Why multi-threading? I see no concurrency in the original algorithm.
There is, in my mind, nothing concurrent about 'yield'.

/Jorgen

--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se R'lyeh wgah'nagl fhtagn!
Nov 3 '08 #8
On Mon, 03 Nov 2008 21:09:58 +0000, Jorgen Grahn wrote:
Why multi-threading? I see no concurrency in the original algorithm.
There is, in my mind, nothing concurrent about 'yield'.
No "real" concurrency but a generator can be seen as independent thread
of code where the generator code is allowed to run when `next()` is
called and stops itself when it ``yield``\s an object. Sort of
cooperative multitasking. The name "yield" is often used in concurrent
code like Java's or Io's `yield()` methods.

Ciao,
Marc 'BlackJack' Rintsch
Nov 3 '08 #9
On Nov 3, 4:13*pm, Marc 'BlackJack' Rintsch <bj_...@gmx.net wrote:
On Mon, 03 Nov 2008 21:09:58 +0000, Jorgen Grahn wrote:
Why multi-threading? *I see no concurrency in the original algorithm.
There is, in my mind, nothing concurrent about 'yield'.

No "real" concurrency but a generator can be seen as independent thread
of code where the generator code is allowed to run when `next()` is
called and stops itself when it ``yield``\s an object. *Sort of
cooperative multitasking. *The name "yield" is often used in concurrent
code like Java's or Io's `yield()` methods.

Ciao,
* * * * Marc 'BlackJack' Rintsch
Further, it resumes where it left off when it gets control again:

"execution is stopped at the yield keyword (returning the result) and
is resumed there when the next element is requested by calling the
next() method" --the fine manual

It maintains and operates in its own separate execution frame, etc.
Nov 3 '08 #10

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

Similar topics

10
5647
by: Talin | last post by:
I'm sure I am not the first person to do this, but I wanted to share this: a generator which returns all permutations of a list: def permute( lst ): if len( lst ) == 1: yield lst else: head = lst for x in permute( lst ): yield head + x
3
7142
by: Jack Middleton | last post by:
Hi! I'm lookin for a faster permutation algorithm for matrices. I know that it can be done with multiplying a matrix with a permutation matrix. It just seems a waste to iterate through all those zeroes. Is there an algorithm for matrixes that is optimized just for permutations? The matrices that I use are fairly small (around 6*6) and I only use positive integers as elements. Thanks for help,
1
623
by: user | last post by:
Hello I have Array of 50 ints. I want to receive random permutation, so in each int will be different number from 0-49. Is there any class for permutation ? Thanx Michal
6
3587
by: Rajesh | last post by:
Hello Everybody, Can anybody help me in writing a C program to generate and print all possible combinations of n numbers. For eg. for 3 numbers(1,2,3) there turn out 3! combinations. (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1).
2
3041
by: robert | last post by:
for the purpose of flat n-dim iteration a function or generator ndim_permute(*v) should compute or generate a list of tuples like: ndim_permute( (0,1,2), (0,1), (0,1), ) -> 0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 1
3
3141
by: weidongtom | last post by:
Hi, I have been working at this problem, and I think I need a permutation algorithm that does the following: Given a list of elements that are either a character or a character follows by a number, e.g.
6
11753
by: badcrusher10 | last post by:
Hello. I'm having trouble figuring out what to do and how to do.. could someone explain to me what I need to do in order to work? THIS IS WHAT I NEED TO DO: Professor Snoop wants a program that will randomly generate 10 unique random numbers. Your job is to write a program that produces random permutations of the numbers 1 to 10. “Permutation” is a mathematical name for an arrangement. For example, there are six permutations of the...
7
4093
by: xirowei | last post by:
Let's say i create a String array that store 4 Alphabets {"A","B","C","D"} How can i get the result if i need permutation of 4P3 and 4P2? I had refer to many examples from the internet, but those examples cannot compute n selection from m elements. They only able to computer permutation of m elements without selection e.g. 4P4. Hence i need guideline in how to compute this kind of permutation. If i use manual calculation of 4P3...
0
1493
by: 249740 | last post by:
Write a program that reads N phrases and determines if one phrase is a permutation of the other. For example: Phrase 1 is: “One World One Dream” Phrase 2 is: “World One One Dream”. Then the output should say that phrase 1 is permutation of phrase 2. Note that spaces/tabs are not counted as characters. Sample Input: 3 One World One Dream World One One Dream No World No Dream Sample Output: Phrase 1 is permutation of Phrase 2
0
9584
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
10583
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
10337
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
10323
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
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6854
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
5525
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
5654
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4301
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

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.