Finding all possible permutations of a given string in python -


i have string. want generate permutations string, changing order of characters in it. example, say:

x='stack' 

what want list this,

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

currently iterating on list cast of string, picking 2 letters randomly , transposing them form new string, , adding set cast of l. based on length of string, calculating number of permutations possible , continuing iterations till set size reaches limit. there must better way this.

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

itertools.permutations(iterable[, r])

return successive r length permutations of elements in iterable.

if r not specified or none, r defaults length of iterable , possible full-length permutations generated.

permutations emitted in lexicographic sort order. so, if input iterable sorted, permutation tuples produced in sorted order.

you'll have join permuted letters strings though.

>>> itertools import permutations >>> perms = [''.join(p) 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 find troubled duplicates, try fitting data structure no duplicates set:

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

thanks @pst pointing out not we'd traditionally think of type cast, more of call set() constructor.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -