SICP subsets exercise in python?

Brian Zhou brian_zhou at agilentNOSPAM.com
Sun Jan 28 20:22:42 EST 2001


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