[Tutor] Recursive permutation
Eivind Triel
ET at cheminova.dk
Thu Nov 18 07:56:33 CET 2004
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']
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@[...].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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20041118/d4970a52/attachment.htm
More information about the Tutor
mailing list