Search code examples
pythonpython-2.7nested-loops

Nested loop through list of sets


I recently read is not a good practice to do the following:

for i in xrange(len(string-or-list)):
    #do something with string-or-list[i]

I get it. But when it comes to nested loops, I don't.

Consider a list of sets h. I want to eliminate all those sets that are subsets of other sets. This is what I did:

for x in xrange(len(h)-1,-1,-1):
    for y in xrange(x):
        if h[x] <= h[y]: h[x] = set()
        elif h[x] > h[y]: h[y], h[x] = h[x], set()
return filter(None, h)

What can I do to make it more pythonic? I though about using reversed and enumerate, but then I don't know how to stop the second loop to the element before x. Or should I do the whole thing differently maybe?

UPDATE

I solved the problem by making the list of sets into a set of tuples, and then I applied

    return [list(s) for s in h if sum(1 for o in h if set(s) <= set(o)) <= 1]

Solution

  • the most pythonic thing would be to compose a new list with the sets you want. To remove duplicates we need a helper function..

    def uniq(seq):
        memo = []
        for i in seq:
            if i not in memo:
                memo.append(i)
                yield i
    

    Then we can do what we want

    return [s for s in uniq(h) if not any(s < o for o in h)]