list of unique non-subset sets

Bengt Richter bokr at oz.net
Sat Mar 19 00:44:41 EST 2005


On 18 Mar 2005 19:41:55 -0800, les_ander at yahoo.com wrote:

>Once again my specs were incomplete.
>By largest I mean exactly what you pointed out as in sum(map(len,
>setlist)).
>
But that will not necessarily yield a single setlist taken from the source set list,
so you still need a selection amongst equals. You can make it explicit, or
you can say you'll take whatever a sort puts at the sorted list extreme, which you
seem to have done ;-)

>I think this might work--sorting of the initial list should do the
>trick.
>1) sort the sets by size (in decending order)
>2) put the first (largest) into a new list (Lu)
>for s in Lnew[1:]:
> keep=True
> for i in range(len( Lun) ):
>   if len(s)==len( s & Lun[i] ):
>     keep=False
>     break
> if keep==True:
>   Lun.append( s )
>
>----------------- here is the complete code
>s1=set(['a','b','c'])
>s2=set(['a','c'])
>s3=set(['a','d','e','f'])
>s4=set(['r','k','l'])
>s5=set(['r','k','l'])
>s6=set(['g', 'h'])
>s7=set(['h', 'i'])
>s8=set(['g', 'h', 'i'])
>
>L=[s1,s2,s3,s4,s5,s6,s7,s8]
>length=[len(s) for s in L]
>L2= sorted(zip(length,range(len(L))))
>Lnew=[L[j] for (i,j) in L2]
>Lnew.reverse()
>Lun=[Lnew[0]]  # list with the result
>for s in Lnew[1:]:
> keep=True
> for i in range(len( Lun) ):
>   if len(s)==len( s & Lun[i] ):
>     keep=False
>     break
> if keep==True:
>   Lun.append( s )
>
>#----------------
>>>> Lun
>[set(['a', 'e', 'd', 'f']), set(['i', 'h', 'g']), set(['k', 'r', 'l']),
>set(['a', 'c', 'b'])]
>
>Seems like I got it.
>
Does it work on
L = [set('abc'), set('def'), set('abcdef')]
?
I get:
  0: []
  6: [set(['a', 'c', 'b']), set(['e', 'd', 'f'])]
  6: [set(['a', 'c', 'b', 'e', 'd', 'f'])]

Your code above:

 >>> L = [set('abc'), set('def'), set('abcdef')]
 >>> length=[len(s) for s in L]
 >>> L2= sorted(zip(length,range(len(L))))
 >>> Lnew=[L[j] for (i,j) in L2]
 >>> Lnew.reverse()
 >>> Lun=[Lnew[0]]  # list with the result
 >>> for s in Lnew[1:]:
 ...  keep=True
 ...  for i in range(len( Lun) ):
 ...    if len(s)==len( s & Lun[i] ):
 ...      keep=False
 ...      break
 ...  if keep==True:
 ...    Lun.append( s )
 ...
 >>> Lun
 [set(['a', 'c', 'b', 'e', 'd', 'f'])]

But your successful set list is not unique in its success value (6) ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list