I would appreciate any help with the following exercise, I have no idea how to really start this it'd not like any of the previous exercises I've done so any help would be great :)

Define a class Set that keeps track of a collection of distinct objects. Inernally, you should use a list as an instance variable, but you should make sure not to allow duplicates into your set. Something like the following design:
_contents
Set() add(value)
__contains__(value) discard(value)

Recommended Answers

All 6 Replies

What do you need help with? Do you know how to define a class yet? Here's some documentation.

Thanks, and yes I know how to define a class I just don't know how to create a class Set that would make a list of distinct objects. I can use list as an instance variable but I can't allow it to have duplicates in the set.

So your add function would need to check if the element was already in the set and if not, add it. Seems pretty straight forward. Maybe you're thinking too hard about it.

Heh yeah maybe I am, I'll post the code up in a bit and hopefully you can give me some advice on it.
There's also a second part where I should define a SortedSet class that ensures that the contents of the set are internally sorted. To verify the order, provide a __str__ method that displays the set.

Another great little trick for classes is providing a __repr__ method, so that when you print the object of a set, instead of displaying a message like this:

>>> class my_class(object):
...     def __init__(self):
...         self.A = '1'
...     
>>> mc = my_class()
>>> mc
<__main__.my_class object at 0x01D24BF0>
>>>

You get this:

>>> class my_class(object):
...     def __init__(self):
...         self.A = '1'
...     def __repr__(self):
...         return 'Hi, my A value is currently %s' % self.A
...     
>>> mc = my_class()
>>> mc
Hi, my A value is currently 1
>>>

Keep in mind that you can make the return value of your repr() function literally anything. It's completely up to you how you want your class object represented.

commented: good explanation +6

There's also a second part where I should define a SortedSet class

Verify with the teacher that the set will only contain integers, floats, and strings, and whether there will be more than one type of these in the set.. If you have lists mixed in with integers mixed in with whatever, sorting gets very tricky.

commented: very good point +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.