[Tutor] Sets
Alan Gauld
alan.gauld@blueyonder.co.uk
Fri Apr 18 17:58:52 2003
> > use a dictionary.
>
> recently began studying set theory), but why is using a dictionary a
> good way to implement sets?
Because a dictionary has a unique key mechanism so if you try
to add duplicate keys it won't work.
So we can build a set based on a dictionary such that:
> According to the set theory text I'm using
> (1) {a, a} = {a}
> (2) {a, b} = {b, a}
Only one entry for 'a' can exist
It doesn't matter which order you put the elements in.
> rid of---or ignore---duplicates? Or would one implement a set where
the
> dictionary's key:value pairs are item:frequency
You could. But frequency should only be one. So I'd just
use key:None pairs
class Set:
def __init__(self,elems = []): self.theSet = dict(elems)
def addElement(self, elem): self.theSet[elem] = None
def members(self): return self.theSet.keys()
def union(self, anotherSet):
return Set(self.theSet.items() + anotherSet.theSet.items())
def isEmpty(self): return len(self.theSet.keys()) == 0
etc...
> Would the null set then be represented by
> my_set = {}
Yes.
HTH,
Alan G.