[Tutor] help with list permutations

Kent Johnson kent37 at tds.net
Fri Jan 4 14:34:05 CET 2008

Chris Fuller wrote:
> This is a good case for recursion. My solution is in two steps.
> Here is the code:
> def recursion_is_your_friend(l):
>    if len(l) == 1:
>       return l
>    else:
>       return [ (i, recursion_is_your_friend(l[1:])) for i in l[0] ]
> l = recursion_is_your_friend([['a','b'],['c','d','e'],['f'],['g','h']])

> The next step is to trace all the paths from the root to the leaves.

You don't have to do this in two steps, you can generate the desired 
list directly. For example:

def recursion_is_your_friend(l):
    if not l:
       return [[]]
       values = [[i] + value
           for i in l[0]
               for value in recursion_is_your_friend(l[1:]) ]
       return values

print recursion_is_your_friend([['a','b'],['c','d','e'],['f'],['g','h']])


More information about the Tutor mailing list