[Tutor] Recursive permutation

Gregor Lingl glingl at aon.at
Thu Nov 18 19:01:00 CET 2004



Eivind Triel schrieb:

> Hi
>  
> I am pusling withe a code that makes all the possible permutations of 
> a string, not only the entire lenght of the string but also 
> len(string) - 1 , -2 etc etc.
>  
> Like this:
> Sting = 123
> This give: 
> ['1','2','3','12','13','21','23','31','32','123','132','213','231,'312',321']

Hi Eivind!

one way to accomplish this could be first to
construct all "subset-strings" of the given string -
in your example this would return

['','1','2','3','12','13','23','123']

Then you can apply your tree-function to each of
these strings.

Regards, Gregor

>  
> Well, I've found this code:
>  
> #!/usr/bin/python
> import sys
>  
> def tree(txt, result=''):
>    if txt:
>      for i in range(len(txt)):
>        tree(txt[:i] + txt[i+1:], result + txt[i])
>    else:
>      print result
>  
> if __name__ == "__main__":
>    tree(list(sys.argv[1]))
>
> #Bob Gailer
> #bgailer@[...].edu <mailto:#bgailer@%5B...%5D.edu>
> #303 442 2625
>  
> Thanx, Bob
>  
> This code maks a permutation of the entire list (all the 3 digs), but 
> how do I make the permutations of lower lists?
> Going one down i seems easy: Remove alle the element one at a time and 
> make a permultation of the rest. But going two down - it's like: 
> Remove [1,2] then [1,3] then [1, ..] then [2,3] then [2,..] then [3,4] 
> then [3,..] etc etc.
> But what i going n'th down like? It seems to be som kind of 
> combination but I just can't get i right.
>  
> Well is there a nice code that will do the trick?
>  
> -Eivind
>  
>  
>  
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>


More information about the Tutor mailing list