Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all possible permutations of a given string in python

I have a string. I want to generate all permutations from that string, by changing the order of characters in it. For example, say:

x='stack' 

what I want is a list like this,

l=['stack','satck','sackt'.......] 

Currently I am iterating on the list cast of the string, picking 2 letters randomly and transposing them to form a new string, and adding it to set cast of l. Based on the length of the string, I am calculating the number of permutations possible and continuing iterations till set size reaches the limit. There must be a better way to do this.

like image 381
Nihar Sarangi Avatar asked Nov 29 '11 06:11

Nihar Sarangi


People also ask

How do you get all the possible combinations of a string?

substring(1); Set<String> qq=find(st); for(String str:qq) { for(int i=0;i<=str. length();i++) { ss. add(comb(str,c,i)); } } } return ss; } public static String comb(String s,char c,int i) { String start=s. substring(0,i); String end=s.

How do you solve permutations in Python?

To calculate permutations in Python, use the itertools. permutation() method. The itertools. permutations() method takes a list, dictionary, tuple, or other iterators as a parameter and returns the permutations of that list.

Is there a permutation function in Python?

Syntax of python permutationsPython has a package called 'itertools' from which we can use the permutations function and apply it on different data types. The number of total permutation possible is equal to the factorial of length (number of elements).


2 Answers

The itertools module has a useful method called permutations(). The documentation says:

itertools.permutations(iterable[, r])

Return successive r length permutations of elements in the iterable.

If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order.

You'll have to join your permuted letters as strings though.

>>> from itertools import permutations >>> perms = [''.join(p) for p in permutations('stack')] >>> perms 

['stack', 'stakc', 'stcak', 'stcka', 'stkac', 'stkca', 'satck', 'satkc', 'sactk', 'sackt', 'saktc', 'sakct', 'sctak', 'sctka', 'scatk', 'scakt', 'sckta', 'sckat', 'sktac', 'sktca', 'skatc', 'skact', 'skcta', 'skcat', 'tsack', 'tsakc', 'tscak', 'tscka', 'tskac', 'tskca', 'tasck', 'taskc', 'tacsk', 'tacks', 'taksc', 'takcs', 'tcsak', 'tcska', 'tcask', 'tcaks', 'tcksa', 'tckas', 'tksac', 'tksca', 'tkasc', 'tkacs', 'tkcsa', 'tkcas', 'astck', 'astkc', 'asctk', 'asckt', 'asktc', 'askct', 'atsck', 'atskc', 'atcsk', 'atcks', 'atksc', 'atkcs', 'acstk', 'acskt', 'actsk', 'actks', 'ackst', 'ackts', 'akstc', 'aksct', 'aktsc', 'aktcs', 'akcst', 'akcts', 'cstak', 'cstka', 'csatk', 'csakt', 'cskta', 'cskat', 'ctsak', 'ctska', 'ctask', 'ctaks', 'ctksa', 'ctkas', 'castk', 'caskt', 'catsk', 'catks', 'cakst', 'cakts', 'cksta', 'cksat', 'cktsa', 'cktas', 'ckast', 'ckats', 'kstac', 'kstca', 'ksatc', 'ksact', 'kscta', 'kscat', 'ktsac', 'ktsca', 'ktasc', 'ktacs', 'ktcsa', 'ktcas', 'kastc', 'kasct', 'katsc', 'katcs', 'kacst', 'kacts', 'kcsta', 'kcsat', 'kctsa', 'kctas', 'kcast', 'kcats']

If you find yourself troubled by duplicates, try fitting your data into a structure with no duplicates like a set:

>>> perms = [''.join(p) for p in permutations('stacks')] >>> len(perms) 720 >>> len(set(perms)) 360 

Thanks to @pst for pointing out that this is not what we'd traditionally think of as a type cast, but more of a call to the set() constructor.

like image 115
machine yearning Avatar answered Oct 06 '22 18:10

machine yearning


You can get all N! permutations without much code

def permutations(string, step = 0):      # if we've gotten to the end, print the permutation     if step == len(string):         print "".join(string)      # everything to the right of step has not been swapped yet     for i in range(step, len(string)):          # copy the string (store as array)         string_copy = [character for character in string]          # swap the current index with the step         string_copy[step], string_copy[i] = string_copy[i], string_copy[step]          # recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1)         permutations(string_copy, step + 1) 
like image 44
illerucis Avatar answered Oct 06 '22 17:10

illerucis