views:

159

answers:

4

Just a quick question, im defining a class were only a set of integers is used. I cannot use the following datatypes in defining my class: set, frozenset and dictionaries.

i need help defining:

remove(self,i): Integer i is removed from the set. An exception is raised if i is not in self.

discard(self, i): integer i is removed from the set. No exception is raised if i is not in self

+1  A: 

I cannot use the following datatypes in defining my class: set, frozenset and dictionaries.

It looks like you are going to use list. You can use list's remove method and handle exceptions in appropriate way.

Li0liQ
+2  A: 

Assuming you are using an internal list based on what you've said, you could do it like so:

class Example(object):
    def __init__(self):
        self._list = list()

    # all your other methods here...

    def remove(self, i):
        try:
            self._list.remove(i)
        except ValueError:
            raise ValueError("i is not in the set.")

    def discard(self, i):
        try:
            self._list.remove(i)
        except ValueError:
            pass

remove() tries to remove the element and catches the list's ValueError so it can throw its own. discard() does the same but instead does nothing if a ValueError occurs.

Evan Fosmark
+1  A: 

Here's highly inefficient but complete implementation using MutableSet ABC:

import collections


class MySet(collections.MutableSet):

    def __init__(self, iterable=tuple()):
        self._items = []
        for value in iterable:
            self.add(value)

    def discard(self, value):
        try: self._items.remove(value)
        except ValueError:
            pass

    def add(self, value):
        if value not in self:
           self._items.append(value)

    def __iter__(self):
        return iter(self._items)

    def __len__(self):
        return len(self._items)

    def __contains__(self, value):
        return value in self._items

From collections.MutableSet source:

def remove(self, value):
    if value not in self:
       raise KeyError(value)
    self.discard(value)
J.F. Sebastian
A: 

Here is something I did with duplication, take some ideas from it

combList = list1 + list2

combList.sort()
last = combList[-1]
for i in range(len(combList)-2, -1, -1):
        if last == combList[i]:
                del combList[i]
        else:
                last = combList[i]

combList.sort()

for i in range(len(combList)):
        print i+1, combList[i]

I totally agreed with LiOliQ, the only way is to do it as a list.

JohnWong