472,809 Members | 3,205 Online

# recursive list comprehension

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
Jul 18 '05 #1
1 4117
"SimonVC" <py****@simon.vc> wrote in message
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/Coo.../Recipe/204297

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

-- Paul
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.