A puzzle for Pythonistas

Alan James Salmoni alan_salmoni at yahoo.com
Sat Feb 1 14:42:20 CET 2003


Thanks Anton - much appreciated.

Alan.

antonmuhin íà rambler.ru <antonmuhin at rambler.ru> wrote in message news:<mailman.1044022985.21542.python-list at python.org>...
> Hello, Alan!
> 
> I'm by no means an expert, but here what I can suggest:
> 
> from __future__ import generators
> 
> def indices(seq):
>     """get all the indices for sequence, just a shortcut"""
>     for i in range(len(seq)):
>         yield i
> 
> def subsets(n):
>     """generate all the subsets (by indices) for n-set"""
>     isInSubset = [0]*n
>     yield []
>     
>     while 1:
>         for i in indices(isInSubset):
>             if isInSubset[i] == 0:
>                 isInSubset[i] = 1
>                 break
>             else:
>                 isInSubset[i] = 0
>         else:
>             raise StopIteration
>             
>         yield [i for i in indices(isInSubset) if isInSubset[i] == 1]
>         
> def problem(l):
>     for indices in subsets(len(l)):
>         part = [l[i] for i in indices]
>         if len(part) > 1:
>             print part
>         
> if __name__ == "__main__":
>     problem(range(4))
> 
> HTH,
> Anton.




More information about the Python-list mailing list