All combinations of a list
Stephen Kloder
stephenk at cc.gatech.edu
Mon Oct 23 07:01:39 EDT 2000
June Kim wrote:
> Below is my first version of doing it:
>
> def comb(list):
> if len(list) ==0:
> return [[]]
> return [ [[list[0]],[]][i]+c for i in (0,1) \
> for c in comb(list[1:]) ]
>
> That works fine, but why does another version using
> lambda give a subscription error?
>
> def comb(list):
> if len(list) ==0:
> return [[]]
> return map(lambda x: [list[0]]+x , comb(list[1:])) \
> + comb(list[1:])
>
> Thanks in advance.
>
> June
>
> [This thread was first started from permutation lists
> and now that the topic has moved somewhat far from
> the originator's question, I open up this thread as a new one]
It does not work because list is not defined as a list inside the
context of lambda. If you had not used a pre-defined name, the error
message would have been NameError. Changing the last line to:
return map(lambda x,list=list: [list[0]]+x , comb(list[1:])) \
+ comb(list[1:])
should do the job.
--
Stephen Kloder | "I say what it occurs to me to say.
stephenk at cc.gatech.edu | More I cannot say."
Phone 404-874-6584 | -- The Man in the Shack
ICQ #65153895 | be :- think.
More information about the Python-list
mailing list