SICP subsets exercise in python?

June Kim junaftnoon at nospamplzyahoo.com
Mon Jan 29 02:22:09 EST 2001


I don't think these are better ways(actually awful in terms of readibility)
but you might find them interesting. They are one-liners.

def subsets(list):
    return list and [ z+c for z in [[list[0]],[]] \
           for c in subsets(list[1:]) or [[]]]

or

def subsets2(list):
    return  list and map(lambda x,list=list: [list[0]]+x ,
subsets2(list[1:]))  \
             + subsets2(list[1:]) or [[]]

Best regards,

June

"Brian Zhou" <brian_zhou at agilentNOSPAM.com> wrote in message
news:980731358.408959 at emperor.labs.agilent.com...
> Thanks Will,
>
> The problem I had was that being a python newbie, I didn't know in python
+
> is used for concat lists. Tried append(), insert(,0) without success. If
you
> happen to use python2.0+, list comprehension make it reads even better.
>
> def subsets(biglist):
>     if [] == biglist:
>         return [[]]
>     else:
>         rest = subsets(biglist[1:])
>         return rest + [[biglist[0]] + x for x in rest]
>
> /Brian
>
> "Will Ware" <wware at world.std.com> wrote in message
> news:G7wDLI.96M at world.std.com...
> > Brian Zhou (brian_zhou at agilentNOSPAM.com) wrote:
> > > Just curious if I can do it easily in Python, kind of give up after a
> few
> > > tries. Anyone?
> >
> > You could do worse than a straightforward translation from Scheme to
> Python:
> >
> > def subsets(biglist):
> >     if not biglist:
> >         return [ [ ] ]
> >     rest = subsets(biglist[1:])
> >     def func(ss, s=biglist[0]):
> >         return [s] + ss
> >     return rest + map(func, rest)
> >
> > There is probably a more idiomatically Pythonic way to do this. I'm
> > too lazy to think of it right now. I'd start by looking for
opportunities
> > to replace recursion with iteration.
> >
> > --
> > import string,time,os;print string.join((lambda x:x[:10]+x[8:])(map(
> > lambda x:string.center("*"*(lambda x:((x<24) ### Seasons Greetings, Will
> Ware
> > *(x-3))+3)(x),24),range(1,28, 2))),"\n") ################
> wware at world.std.com
>
>




More information about the Python-list mailing list