I understand the gist of the code, that it forms permutations; however, I was wondering if someone could explain exactly what is going on in the return statement.
def perm(l):
sz = len(l)
print (l)
if sz <= 1:
print ('sz <= 1')
return [l]
return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]
This
returnis returning a list comprehension whose items are made by inserting the first item oflinto each position ofp, from the first to the last —pin turn is a list of lists, obtained by a recursive call topermwhich excludes the first item ofl(and thus permutes all other items in all possible ways).If you don’t understand recursion, it’s not really trivial to explain;-). If you don’t understand list comprehensions, they are trivial to explain — that
returnis semantically equivalent tothis also shows how inefficient this code is: it’s calling
permrecursivelysztimes, and obviously there’s no need for it. Much better would be to simply swap the twoforloops:and the equivalent of this, much better code, is a list comprehension with the two
forclauses swapped: