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

Home Posts Topics Members FAQ

Permutation over a list with selected elements

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.

['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2']

find all the permutations that are given by switching the positions of
the elements that:
(1) begins with the same letter, and
(2) follows by a number.

With the above list, some possible permutations are:

['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2']
['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1']
['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1']

Can anyone help me out? Thanks in advance.

Jun 19 '07 #1
3 3141
we********@gmai l.com <we********@gma il.comwrote:
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.

['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2']

find all the permutations that are given by switching the positions of
the elements that:
(1) begins with the same letter, and
(2) follows by a number.

With the above list, some possible permutations are:

['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2']
['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1']
['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1']

Can anyone help me out? Thanks in advance.
I would proceed in 2 steps:
1. find all the sets of indices that are to be permuted
2. produce all the permutations given said sets

Now (1) is pretty easy:

import collections

def find_sets_of_in dices_to_permut e(L):
set_by_letter = collections.def aultdict(list)
for i, elem in enumerate(L):
if len(elem)>1:
set_by_letter[elem[0]].append(i)
return set_by_letter.v alues()

For (2), it looks like we need 2 sub-steps:

2.1. do all permutations of a list given ONE set of indices to permute
2.2. apply the function sub (2.1) to all the sets of indices to permute

let's do 2.1 the lazy way, i.e., recursively:

def all_permutation s_given_indices (L, indices):
yield L
if len(indices) < 2:
return
x = indices.pop()
pivot = L[x]
for y in indices:
L[x] = L[y]
L[y] = pivot
for permut in all_permutation s_given_indices (L, indices):
yield permut
L[y] = L[x]
L[x] = pivot
indices.append( x)

This suggests doing 2.2 recursively as well:

def all_permutation s_with_constrai nts(L, constraints):
if len(constraints ) == 1:
for p in all_permutation s_given_indices (L, constraints[0]):
yield L
return
indices = constraints.pop ()
for p in all_permutation s_given_indices (L, indices):
for pp in all_permutation s_with_constrai nts(p, constraints):
yield pp
constraints.app end(indices)

and, putting it all together:

def do_it_all(L):
sets_of_indices = find_sets_of_in dices_to_permut e(L)
for p in all_permutation s_with_constrai nts(L, sets_of_indices ):
print p

Applied to your example list, this gives:

brain:~ alex$ python cp.py
['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2']
['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2']
['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1']
['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1']
Warning: untested beyond this single run, and _definitely_ not optimal
in either clarity, style, or speed -- just a quick hack to get you
started.
Alex
Jun 20 '07 #2
On Jun 20, 12:37 pm, a...@mac.com (Alex Martelli) wrote:
weidong...@gmai l.com <weidong...@gma il.comwrote:
Hi,
I have been working at this problem, and I think I need apermutation
algorithm that does
the following:
Given a list of elements that are either a character or a character
follows by a number, e.g.
['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2']
find all the permutations that are given by switching the positions of
the elements that:
(1) begins with the same letter, and
(2) follows by a number.
With the above list, some possible permutations are:
['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2']
['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1']
['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1']
Can anyone help me out? Thanks in advance.

I would proceed in 2 steps:
1. find all the sets of indices that are to be permuted
2. produce all the permutations given said sets

Now (1) is pretty easy:

import collections

def find_sets_of_in dices_to_permut e(L):
set_by_letter = collections.def aultdict(list)
for i, elem in enumerate(L):
if len(elem)>1:
set_by_letter[elem[0]].append(i)
return set_by_letter.v alues()

For (2), it looks like we need 2 sub-steps:

2.1. do all permutations of a list given ONE set of indices to permute
2.2. apply the function sub (2.1) to all the sets of indices to permute

let's do 2.1 the lazy way, i.e., recursively:

def all_permutation s_given_indices (L, indices):
yield L
if len(indices) < 2:
return
x = indices.pop()
pivot = L[x]
for y in indices:
L[x] = L[y]
L[y] = pivot
for permut in all_permutation s_given_indices (L, indices):
yield permut
L[y] = L[x]
L[x] = pivot
indices.append( x)

This suggests doing 2.2 recursively as well:

def all_permutation s_with_constrai nts(L, constraints):
if len(constraints ) == 1:
for p in all_permutation s_given_indices (L, constraints[0]):
yield L
return
indices = constraints.pop ()
for p in all_permutation s_given_indices (L, indices):
for pp in all_permutation s_with_constrai nts(p, constraints):
yield pp
constraints.app end(indices)

and, putting it all together:

def do_it_all(L):
sets_of_indices = find_sets_of_in dices_to_permut e(L)
for p in all_permutation s_with_constrai nts(L, sets_of_indices ):
print p

Applied to your example list, this gives:

brain:~ alex$ python cp.py
['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2']
['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2']
['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1']
['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1']

Warning: untested beyond this single run, and _definitely_ not optimal
in either clarity, style, or speed -- just a quick hack to get you
started.

Alex
Thanks.

Jun 20 '07 #3
we********@gmai l.com wrote:
Given a list of elements that are either a character or a character
follows by a number, e.g.

['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2']

find all the permutations that are given by switching the positions of
the elements that:
(1) begins with the same letter, and
(2) follows by a number.

With the above list, some possible permutations are:

['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2']
['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1']
['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1']
Another idea, untested. Also I am not sure whether sequences types are
supposed to be returning functions ...

A.

from operator import mul
from collections import defaultdict

class Swapper:
"""
Given a set of indices this class returns functions
which will swap elements in a list *in place*.
Each function corresponds to a permutation of the
set of indices.
"""

def __init__(self,L ):
self.L = L
self.n = reduce(mul,rang e(2,len(L)+1),1 ) #faculty

def __getitem__(sel f,i):
L = self.L
if not -1<i<self.n:
raise IndexError
def func(R):
Q = perm([R[j] for j in L],i)
for j,x in zip(L,Q):
R[j] = x
return func

def perm(L,m):
#permutation m of list L
res = []
T = L[::-1]
for i in range(len(L),0,-1):
res.append(T.po p(m%i))
m /= i
return res[::-1]

def cross(args):
#Raymond Hettinger's cross product function from ASPN
ans = [[]]
for arg in args:
ans = [x+[y] for x in ans for y in arg]
return ans

def find_sets_of_in dices_to_permut e(L):
set_by_letter = defaultdict(lis t)
for i, elem in enumerate(L):
if len(elem)>1:
set_by_letter[elem[0]].append(i)
return set_by_letter.v alues()

def test():
L = ['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2']
I = find_sets_of_in dices_to_permut e(L) #Alex Martelli's function
M = map(Swapper,I)
for F in cross(M):
# conserve the original list because
#the functions modify a list in place
R = list(L)
# apply each permutation function one by one,
# each is acting on a different set of indices
for fn in F:
fn(R)
print R

if __name__=='__ma in__':
test()
Jun 20 '07 #4

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

Similar topics

5
1972
by: radio | last post by:
I have a list box populated with some groups. All groups have a list of related offices; I have these in the following xml format: <Location>My Group 1</Location> <Location Group="My Group 1">Office 1</Location> <Location Group="My Group 1">Office 2</Location> <Location>My Group 2</Location> <Location Group="My Group 2">Office 1</Location> <Location Group="My Group 2">Office 2</Location> I have the following select box:
5
3472
by: Nick Calladine | last post by:
Learning : Loop to list all dropdown box values on a form Can some one point me in the right direction : I have a form which I want to loop through I basically want to get all the selected values of the option tag see example below
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).
1
4392
by: Christina | last post by:
Hi, I've been looking at some code for dependent list boxes to adapt to a State and City list. There will only be 2 states for the first list box, and 3 cities in the second list box. When the state is selected, the relative cities appear in the second box. I found a nice set of code online that was derived from Dreamweaver code and have altered it to simplify for my minimal needs. I have learned a lot of coding from looking at...
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
9706
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
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
9160
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
5654
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3822
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.