list of unique non-subset sets

Peter Otten __peter__ at web.de
Thu Mar 17 22:58:57 CET 2005


Steven Bethard wrote:

> Can you just do:
> 
> py> def uniq(lst):
> ...     result = []
> ...     for s1 in sorted(lst, reverse=True):
> ...         for s2 in result:
> ...             if s1 <= s2:
> ...                 break
> ...         else:
> ...             result.append(s1)
> ...     return result
> ...
> py> lst = [set(['a','b','c']),
> ...        set(['a','c']),
> ...        set(['a','d','e','f']),
> ...        set(['r','k','l']),
> ...        set(['r','k','l']),
> ...        set(['g', 'h']),
> ...        set(['h', 'i']),
> ...        set(['g', 'h', 'i'])]
> py> uniq(lst)
> [set(['a', 'c', 'b']), set(['a', 'e', 'd', 'f']), set(['k', 'r', 'l']),
> set(['i', 'h', 'g'])]

No, you can't:

"""Since sets only define partial ordering (subset relationships), the
output of the list.sort() method is undefined for lists of sets. 
""" 

Maybe you could just change the above code to

...
for s1 in sorted(lst, key=len, reverse=True):
...
 
> Haven't thought about it too hard though...

Same here.

Peter




More information about the Python-list mailing list