[Tutor] permutations using list comprehensions

Logesh Pillay logesh at iafrica.com
Sun May 1 20:53:26 CEST 2005


Dear list

I was really impressed by this version of quicksort:-
def qsort (t):
    if len (t) == 0:
        return []
    else:
        return qsort([x for x in t[1:] if x <= t[0]]) + [t[0]] + 
qsort([x for x in t[1:] if x > t[0]])

I'm trying to produce something of a similar structure to generate the 
permutations of a sequence by translating the ffg bit of Haskell:-
perms [] = [[]]
perms xs = [ x : ps | x <- xs , ps <- perms ( xs\\[x]) ]

'\\' applies to lists & means elements of the first list excluding any 
elements in common with the second list.

The best I've been able to do is pretty obvious:-
def perms (t):
    if len (t) == 0:
        return []
    else:
        return [[x] + perms ([y for y in t if y <> x]) for x in t]
       
Needless to say, it doesn't work.  It does produce a list of lists but 
they are so horribly nested that I've no idea whether I am getting 
close.  I've also tried adding and removing square brackets in various 
combinations.

Any ideas?

Logesh



More information about the Tutor mailing list