Rustom Mody <rustompm...@gmail.com> writes: > Here is some code I (tried) to write in class the other day > > The basic problem is of generating combinations <snip> > Now thats neat as far as it goes but combinations are fundamentally sets > not lists > > So I thought python would do a better job > I tried translating it to python and sets but it turned out more annoying than > helpful > Can someone improve it?? > > The straightforward translation of the above > Which is ok so far > > > def c(n,r): > if r == 0: > return [[]] > elif len(n) == 0: > return [] > else: > return [[n[0]] + l for l in c(n[1:],r-1)] + c(n[1:],r) > > > Now to go from returning list of lists to set of sets:
def cs(n, r): if r == 0: return [set()] elif len(n) == 0: return [] else: return [set([n[0]]) | l for l in cs(n[1:], r-1)] + cs(n[1:], r) ? It's not so neat if you also want n to be a set rather than a list because the set equivalents of n[0] and n[1:] are a but more complex but it's not that bad: def css(n,r): if r == 0: return [set()] elif len(n) == 0: return [] else: rest = n.copy() e = rest.pop() return [set([e]) | l for l in css(rest, r-1)] + css(rest, r) <snip> -- Ben. -- https://mail.python.org/mailman/listinfo/python-list