[Tutor] Permutations? (original) (raw)
Rich Krauter rmkrauter at yahoo.com
Sun Jul 25 16:21:34 CEST 2004
- Previous message: [Tutor] Permutations?
- Next message: [Tutor] Permutations?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Sun, 2004-07-25 at 03:40, Hee-Seng Kye wrote:
def perm(k): # Compute the list of all permutations of k if len(k) <= 1: return [k] r = [] for i in range(len(k)): s = k[:i] + k[i+1:] p = perm(s) for x in p: r.append(k[i:i+1] + x) return r
Could someone tell me how I can modify the above function so that it produces a list of permutations of k that only begins on k[0]? If k = [0,1,2,3], I want to modify perm(k) so that it only produces [[0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1]].
You could just call your function as-is with a slice of the original list, and then append the initial list element(s) to the results:
lst = [0,1,2,3] results = perm(lst[1:]) print map(lambda res,i=lst[0]:[i]+res,results)
Good luck.
Rich
- Previous message: [Tutor] Permutations?
- Next message: [Tutor] Permutations?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]