recursive list comprehension

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Aug 9 09:12:43 EDT 2004


"SimonVC" <python at simon.vc> wrote in message
news:fa156589.0408090402.5ef3c40b at posting.google.com...
> Is there a way to do this as a list comprehension?
>
> >>> def recu(alist, blist=[]):
> ...     if len(alist)==0: print blist
> ...     for i in range(len(alist)):
> ...             blist.append(alist.pop(i))
> ...             recu(alist, blist)
> ...             alist.insert(i, blist.pop())
>
> >>> recu(list("abc"))
> ['a', 'b', 'c']
> ['a', 'c', 'b']
> ['b', 'a', 'c']
> ['b', 'c', 'a']
> ['c', 'a', 'b']
> ['c', 'b', 'a']
>
>
> Cheers
>   SimonVC
>
> keywords: python recursive permutations algorithm combination jumble

Perhaps this cookbook recipe would be of help to you:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297

It describes how to access the current list comp from within the list comp
itself.

-- Paul





More information about the Python-list mailing list