[Tutor] Sets

Magnus Lyckå magnus@thinkware.se
Fri Apr 18 09:49:02 2003

At Fri, 18 Apr 2003 02:57:41 -0500, Norvell Spearman wrote:

>On Thursday, 2003.04.17, 19:23:47 -0700, Sean 'Shaleh' Perry wrote:
> > On Thursday 17 April 2003 17:32, Brian Christopher Robinson wrote:
> > > I think I read that sets will be a primitive data type in the next 
> version
> > > of Python, but what is a good way to implement them now?
> >
> > use a dictionary.

That's a slightly terse explanation...

>Not that I know a better implementation (I'm new to Python and only
>recently began studying set theory), but why is using a dictionary a
>good way to implement sets?  According to the set theory text I'm using
>(and this is the text's notation, not Python code):
>     (1) {a, a} = {a}
>     (2) {a, b} = {b, a}


>Since dictionaries are unordered (2) above is covered, but wouldn't (1)
>(if one creates a set class using a dictionary) require a method to get
>rid of---or ignore---duplicates?

No. You store the items in the set as keys in the dictionary.
The same key can't occur twice.

>Or would one implement a set where the
>dictionary's key:value pairs are item:frequency and two sets are equal
>if their respective dictionaries contain the same items, ignoring
>frequencies > 0?

In a simple set class, you could just store 1, or whatever
as value. Storing a frequency is an extension to the set
behaviour you described above, but it's used now and then.
Such a class is often called a "bag" or a "multiset".

>Would the null set then be represented by
>     my_set = {}

Well, wrapped in a class, but yes, that looks empty
to me.

>Or am I using ``sets'' in the wrong context?


I searched google for "python set class". For instance, I found these:


(Not using dict, since it has to store mutable objects)