On Jan 10, 7:25 am, Jason Grout <[email protected]> wrote:
> John H Palmieri wrote:
> >
> > Here's another question: what is the most efficient way of testing
> > whether one Set is a subset of another?  I can do
>
> >     S in list(T.subsets())
>
> > -- and it's a bit frustrating that I can't do S in T.subsets() -- and
> > I can also manipulate intersections, unions, differences, etc. I can
> > also convert to python sets and use <=.  Is there a preferred way?
>
> You could use
>
> all(s in T for s in S)
>
> to do the job.  It might be faster to use another mechanism, but the
> above does shortcut (i.e., it stops when an element is found in S that
> is not in T).
>
> Alternatively, you could calculate the set difference S \ T and check
> that is empty; that might be faster.
>
> Do you know how to use the timeit command?
>
> sage: timeit('all(s in T for s in S)')
> 625 loops, best of 3: 10.1 µs per loop
> sage: timeit('S.difference(T)==Set([])')
> 625 loops, best of 3: 26.2 µs per loop
> sage: timeit('len(S.difference(T))==0')
> 625 loops, best of 3: 21.4 µs per loop
>
> Python still has this beat, though:
>
> sage: S_python = set(S)
> sage: T_python = set(T)
> sage: timeit('S_python.issubset(T_python)')
> 625 loops, best of 3: 755 ns per loop

However

sage: timeit('set(S).issubset(set(T))')

gives me very similar times to the first option (all(s in T for s in
S)).  So if I start with Sage sets, I don't seem to gain much by
converting back to python sets for this (not to mention that if S = Set
(ZZ), then set(S) runs into problems...).

  John

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to