A puzzle for Pythonistas

antonmuhin íà rambler.ru antonmuhin at rambler.ru
Fri Jan 31 15:21:27 CET 2003


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