Пример #1
0
 def __init__(self, n):
     """
     (MultisetAsLinkedList, int) -> None
     Constructs a multiset with the given universe size.
     """
     super(MultisetAsLinkedList, self).__init__(n)
     self._list = LinkedList()
Пример #2
0
 def purge(self):
     """
     (BinomialQueue) -> None
     Purges this binomial queue.
     """
     self._treeList = LinkedList()
     self._count = 0
Пример #3
0
 def __init__(self):
     """
     (OrderedListAsLinkedList) -> None
     Constructs an ordered list.
     """
     super(OrderedListAsLinkedList, self).__init__()
     self._linkedList = LinkedList()
Пример #4
0
 def purge(self):
     """
     (OrderedListAsLinkedList) -> None
     Purges this ordered list.
     """
     self._linkedList = LinkedList()
     self._count = 0
Пример #5
0
 def merge(self, queue):
     """
     (BinomialQueue, BinomialQueue) -> None
     Merges the contents of the given binomial queue
     with this binomial queue.
     """
     oldList = self._treeList
     self._treeList = LinkedList()
     self._count = 0
     p = oldList.head
     q = queue._treeList.head
     carry = None
     i = 0
     while p is not None or q is not None \
             or carry is not None:
         a = None
         if p is not None:
             tree = p.datum
             if tree.degree == i:
                 a = tree
                 p = p.__next__
         b = None
         if q is not None:
             tree = q.datum
             if tree.degree == i:
                 b = tree
                 q = q.__next__
         (sum, carry) = BinomialQueue.fullAdder(a, b, carry)
         if sum is not None:
             self.addTree(sum)
         i += 1
     queue.purge()
Пример #6
0
 def __init__(self):
     """
     (QueueAsLinkedList) -> None
     Constructs a queue.
     """
     super(QueueAsLinkedList, self).__init__()
     self._list = LinkedList()
Пример #7
0
 def __init__(self):
     """
     (StackAsLinkedList)
     Constructs a stack.
     """
     super(StackAsLinkedList, self).__init__()
     self._list = LinkedList()
Пример #8
0
 def __init__(self, key):
     """
     (GeneralTree, Object) -> None
     Constructs a general tree with the given object at its root.
     """
     super(GeneralTree, self).__init__()
     self._key = key
     self._degree = 0
     self._list = LinkedList()
Пример #9
0
  class ReverseVisitor(Visitor):
    def __init__(self):
      self._list = LinkedList()

    def visit(self, obj):
      self._list.prepend(obj)

    def getList(self):
      return self._list

    list = property(
        fget = lambda self: self.getList())
Пример #10
0
 def __init__(self, *args):
     """
     (BinomialQueue, ...) -> None
     Constructor.
     """
     super(BinomialQueue, self).__init__()
     self._treeList = LinkedList()
     if len(args) == 0:
         pass
     elif len(args) == 1:
         assert isinstance(args[0], self.BinomialTree)
         self._treeList.append(args[0])
     else:
         raise ValueError
Пример #11
0
 def __init__(self):
     """
     (QueueAsLinkedList) -> None
     Constructs a queue.
     """
     super(QueueAsLinkedList, self).__init__()
     self._list = LinkedList()
 def __init__(self, n):
     """
     (MultisetAsLinkedList, int) -> None
     Constructs a multiset with the given universe size.
     """
     super(MultisetAsLinkedList, self).__init__(n)
     self._list = LinkedList()
Пример #13
0
 def merge(self, queue):
     """
     (BinomialQueue, BinomialQueue) -> None
     Merges the contents of the given binomial queue
     with this binomial queue.
     """
     oldList = self._treeList
     self._treeList = LinkedList()
     self._count = 0
     p = oldList.head
     q = queue._treeList.head
     carry = None
     i = 0
     while p is not None or q is not None \
             or carry is not None:
         a = None
         if p is not None:
             tree = p.datum
             if tree.degree == i:
                 a = tree
                 p = p.next
         b = None
         if q is not None:
             tree = q.datum
             if tree.degree == i:
                 b = tree
                 q = q.next
         (sum, carry) = BinomialQueue.fullAdder(a, b, carry)
         if sum is not None:
             self.addTree(sum)
         i += 1
     queue.purge()
Пример #14
0
 def purge(self):
     """
     (BinomialQueue) -> None
     Purges this binomial queue.
     """
     self._treeList = LinkedList()
     self._count = 0
Пример #15
0
 def __init__(self):
     """
     (OrderedListAsLinkedList) -> None
     Constructs an ordered list.
     """
     super(OrderedListAsLinkedList, self).__init__()
     self._linkedList = LinkedList()
Пример #16
0
 def purge(self):
     """
     (OrderedListAsLinkedList) -> None
     Purges this ordered list.
     """
     self._linkedList = LinkedList()
     self._count = 0
Пример #17
0
 def __init__(self):
     """
     (StackAsLinkedList)
     Constructs a stack.
     """
     super(StackAsLinkedList, self).__init__()
     self._list = LinkedList()
Пример #18
0
 def __init__(self, size):
     """
     (GraphAsLists, int) -> None
     Constructs a graph with the given maximum number of vertices.
     """
     super(GraphAsLists, self).__init__(size)
     self._adjacencyList = Array(size)
     for i in range(size):
         self._adjacencyList[i] = LinkedList()
Пример #19
0
 def __init__(self, key):
     """
     (GeneralTree, Object) -> None
     Constructs a general tree with the given object at its root.
     """
     super(GeneralTree, self).__init__()
     self._key = key
     self._degree = 0
     self._list = LinkedList()
Пример #20
0
 def __init__(self, length):
     """
     (ChainedHashTable, int) -> None
     Constructs a chained hash table with the given length.
     """
     super(ChainedHashTable, self).__init__()
     self._array = Array(length)
     for i in xrange(len(self._array)):
         self._array[i] = LinkedList()
Пример #21
0
 def __init__(self, numberOfRows, numberOfColumns):
     """
     (SparseMatrixAsLinkedList, int, int) -> None
     Constructs a sparse matrix with the given number of rows and columns.
     """
     super(SparseMatrixAsLinkedList, self).__init__(numberOfRows,
                                                    numberOfColumns)
     self._lists = Array(numberOfRows)
     for i in xrange(numberOfRows):
         self._lists[i] = LinkedList()
Пример #22
0
    def __init__(self, *args):
        """
        (BinomialQueue, ...) -> None
        Constructor.
        """
        super(BinomialQueue, self).__init__()
        self._treeList = LinkedList()
	if len(args) == 0:
	    pass
	elif len(args) == 1:
	    assert isinstance(args[0], self.BinomialTree)
	    self._treeList.append(args[0])
	else:
	    raise ValueError
Пример #23
0
class QueueAsLinkedList(Queue):
    """
    Queue implemented using a linked list.
    """

#}@head

#{

    # ...
#}@tail


#{
    def __init__(self):
        """
        (QueueAsLinkedList) -> None
        Constructs a queue.
        """
        super(QueueAsLinkedList, self).__init__()
        self._list = LinkedList()

    def purge(self):
        """
        (QueueAsLinkedList) -> None
        Purges this queue.
        """
        self._list.purge()
        self._count = 0
#}>a

#{
    def getHead(self):
        """
        (QueueAsLinkedList) -> Object
        Returns the object at the head of this queue.
        """
        if self._count == 0:
            raise ContainerEmpty
        return self._list.first

    def enqueue(self, obj):
        """
        (QueueAsLinkedList, Object) -> None
        Enqueues the given object to the tail of this queue.
        """
        self._list.append(obj)
        self._count += 1

    def dequeue(self):
        """
        (QueueAsLinkedList) -> Object
        Dequeues the object at the head of this queue.
        """
        if self._count == 0:
            raise ContainerEmpty
        result = self._list.first
        self._list.extract(result)
        self._count -= 1
        return result
#}>b

    def accept(self, visitor):
        """
        (QueueAsLinkedList, Visitor) -> None
        Makes the given visitor visit all the objects in this queue.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._list.head
        while ptr is not None:
            visitor.visit(ptr.datum)
            if visitor.isDone:
                return
            ptr = ptr.next

    class Iterator(Iterator):
        """
        Enumerates the elements of a QueueAsLinkedList.
        """

        def __init__(self, queue):
            """
            (QueueAsLinkedList.Iterator, QueueAsLinkedList) -> None
            Constructs an iterator for the given queue.
            """
            super(QueueAsLinkedList.Iterator).__init__(queue)
            self._position = None

        def next(self):
            """
            (QueueAsLinkedList.Iterator) -> Object
            Returns the next element.
            """
            if self._position is None:
                self._position = self._container._list.head
            else:
                self._position = self._position.next
            if self._position is None:
                raise StopIteration
            return self._position.datum

    def __iter__(self):
        """
        (QueueAsLinkedList) -> QueueAsLinkedList.Iterator
        Returns an iterator for this queue.
        """
        return self.Iterator(self)

    def _compareTo(self, obj):
        """
        (QueueAsLinkedList, QueueAsLinkedList) -> int

        Comparse this queue with the given queue.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    def main(*argv):
        "QueueAsLinkedList test program."
        print QueueAsLinkedList.main.__doc__
        queue2 = QueueAsLinkedList()
        Queue.test(queue2)
        return 0
    main = staticmethod(main)
Пример #24
0
class StackAsLinkedList(Stack):
    """
    Stack implemented using a linked list.
    """

    #}@head

    #{

    # ...
    #}@tail

    #{
    def __init__(self):
        """
        (StackAsLinkedList)
        Constructs a stack.
        """
        super(StackAsLinkedList, self).__init__()
        self._list = LinkedList()

    def purge(self):
        """
        (StackAsLinkedList) -> None
        Purges this stack.
        """
        self._list.purge()
        self._count = 0
#}>a

#{

    def push(self, obj):
        """
        (StackAsLinkedList, Object) -> None
        Pushes the given object on to this stack.
        """
        self._list.prepend(obj)
        self._count += 1

    def pop(self):
        """
        (StackAsLinkedList) -> None
        Pops the top object off this stack.
        """
        if self._count == 0:
            raise ContainerEmpty
        result = self._list.first
        self._list.extract(result)
        self._count -= 1
        return result

    def getTop(self):
        """
        (StackAsLinkedList) -> None
        Returns the object at the top of this stack.
        """
        if self._count == 0:
            raise ContainerEmpty
        return self._list.first
#}>b

#{

    def accept(self, visitor):
        """
        (StackAsLinkedList, Visitor) -> None
        Makes the given visitor visit all the objects in this stack.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._list.head
        while ptr is not None:
            visitor.visit(ptr.datum)
            if visitor.isDone:
                return
            ptr = ptr.next
#}>c

#{

    class Iterator(Iterator):
        """
        Enumerates the elements of a StackAsLinkedList.
        """
        def __init__(self, stack):
            """
            (StackAsLinkedList.Iterator, StackAsLinkedList) -> None
            Constructs an iterator for the given stack.
            """
            super(StackAsLinkedList.Iterator, self).__init__(stack)
            self._position = stack._list.head

        def next(self):
            """
            (StackAsLinkedList.Iterator) -> Object
            Returns the next element.
            """
            if self._position is None:
                raise StopIteration
            element = self._position
            self._position = self._position.next
            return element.datum

    def __iter__(self):
        """
        (StackAsLinkedList) -> StackAsLinkedList.Iterator
        Returns an iterator for this stack.
        """
        return self.Iterator(self)


#}>d

    def _compareTo(self, obj):
        """
        (StackAsLinkedList, StackAsLinkedList) -> int

        Compares this stack with the given stack.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "StackAsLinkedList test program."
        print StackAsLinkedList.main.__doc__
        stack2 = StackAsLinkedList()
        Stack.test(stack2)
        return 0
 def purge(self):
     """
     (MultisetAsLinkedList) -> None
     Purges this multiset.
     """
     self._list = LinkedList()
Пример #26
0
class BinomialQueue(MergeablePriorityQueue):
    """
    Mergeable priority queue implemented as a binomial queue.
    """

#}@head

#{

    # ...
#}@tail

#{
    def __init__(self, *args):
        """
        (BinomialQueue, ...) -> None
        Constructor.
        """
        super(BinomialQueue, self).__init__()
        self._treeList = LinkedList()
	if len(args) == 0:
	    pass
	elif len(args) == 1:
	    assert isinstance(args[0], self.BinomialTree)
	    self._treeList.append(args[0])
	else:
	    raise ValueError
#}>a


#{
    def addTree(self, tree):
        """
        (BinomialQueue, BinomialQueue.BinomialTree) -> None
        Adds the given binomial tree to this binomial queue.
        """
        self._treeList.append(tree)
        self._count += tree.count

    def removeTree(self, tree):
        """
        (BinomialQueue, BinomialQueue.BinomialTree) -> None
        Removes the given binomial tree from this binomial queue.
        """
        self._treeList.extract(tree)
        self._count -= tree.count
#}>b

    def purge(self):
        """
        (BinomialQueue) -> None
        Purges this binomial queue.
        """
        self._treeList = LinkedList()
        self._count = 0

    def accept(self, visitor):
        """
        (BinomialQueue, Visitor) -> None
        Makes the given visitor visit the elements of this binomial queue.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._treeList.head
        while ptr is not None:
            tree = ptr.datum
            tree.depthFirstTraversal(PreOrder(visitor))
            ptr = ptr.next

#{
    def getMinTree(self):
        """
        (BinomialQueue) -> BinomialQueue.BinomialTree
        Returns the binomial tree in this binomial queue
        with the smallest root.
        """
        minTree = None
        ptr = self._treeList.head
        while ptr is not None:
            tree = ptr.datum
            if minTree is None or tree.key < minTree.key:
                minTree = tree
            ptr = ptr.next
        return minTree

    minTree = property(
        fget = lambda self: self.getMinTree())

    def getMin(self):
        """
        (BinomialQueue) -> Object
        Returns the object in this binomial queue with the smallest value.
        """
        if self._count == 0:
            raise ContainerEmpty
        return self.minTree.key
#}>c

#{
    def merge(self, queue):
        """
        (BinomialQueue, BinomialQueue) -> None
        Merges the contents of the given binomial queue
        with this binomial queue.
        """
        oldList = self._treeList
        self._treeList = LinkedList()
        self._count = 0
        p = oldList.head
        q = queue._treeList.head
        carry = None
        i = 0
        while p is not None or q is not None \
                or carry is not None:
            a = None
            if p is not None:
                tree = p.datum
                if tree.degree == i:
                    a = tree
                    p = p.next
            b = None
            if q is not None:
                tree = q.datum
                if tree.degree == i:
                    b = tree
                    q = q.next
            (sum, carry) = BinomialQueue.fullAdder(a, b, carry)
            if sum is not None:
                self.addTree(sum)
            i += 1
        queue.purge()
#}>d


#{
    @staticmethod
    def fullAdder(a, b, c):
	"""
        (BinomialTree, BinomialTree, BinomialTree) ->
	    (BinomialTree, BinomialTree)
        Returns the (sum, carry) of the given binomial trees.
	"""
	if a is None:
	    if b is None:
		if c is None:
		    return (None, None)
		else:
		    return (c, None)
	    else:
		if c is None:
		    return (b, None)
		else:
		    return (None, b.add(c))
	else:
	    if b is None:
		if c is None:
		    return (a, None)
		else:
		    return (None, a.add(c))
	    else:
		if c is None:
		    return (None, a.add(b))
		else:
		    return (c, a.add(b))
#}>e

#{
    def enqueue(self, obj):
        """
        (BinomialQueue, Object) -> None
        Enqueues the given object in this binomial queue.
        """
        self.merge(BinomialQueue(
	    BinomialQueue.BinomialTree(obj)))
#}>f

#{
    def dequeueMin(self):
        """
        (BinomialQueue) -> Object
        Dequeues and returns the object in this binomial queue
        with the smallest value.
        """
        if self._count == 0:
            raise ContainerEmpty
        minTree = self.minTree
        self.removeTree(minTree)
        queue = BinomialQueue()
        while minTree.degree > 0:
            child = minTree.getSubtree(0)
            minTree.detachSubtree(child)
            queue.addTree(child)
        self.merge(queue)
        return minTree.key
#}>g

    def __str__(self):
        """
        (BinomialQueue) -> str
        Returns a string representation of this binomial queue.
        """
        result = self.__class__.__name__ + " {\n"
        ptr = self._treeList.head
        while ptr is not None:
            result = result + str(ptr.datum) + "\n"
            ptr = ptr.next
        result = result + "}"
        return result

#{
    class BinomialTree(GeneralTree):
        """
        A binomial tree implemented as a general tree.
        """

#}@head

#{

        # ...
#}@tail

#{
        def __init__(self, key):
            """
            (BinomialQueue.BinomialTree, Object) -> None
            Constructor.
            """
            super(BinomialQueue.BinomialTree, self).__init__(key)
#}>h

        def getCount(self):
            """
            (BinomialQueue.BinomialTree) -> int
            Returns the number of objects in this binomial tree.
            """
            return 1 << self._degree

        def swapContentsWith(self, tree):
            """
            (BinomialQueue.BinomialTree, BinomialQueue.BinomialTree) -> None
            Swaps the contents of this binomial tree
            with the given binomial tree.
            """
            tmp = self._key
            self._key = tree._key
            tree._key = tmp
            tmp = self._list
            self._list = tree._list
            tree._list = tmp
            tmp = self._degree
            self._degree = tree._degree
            tree._degree = tmp

#{
        def add(self, tree):
            """
            (BinomialQueue.BinomialTree, BinomialQueue.BinomialTree) ->
                BinomialQueue.BinomialTree
            Adds this binomail tree and the given binomial tree.
            """
            if self._degree != tree._degree:
                raise ValueError
            if self._key > tree._key:
                self.swapContentsWith(tree)
            self.attachSubtree(tree)
            return self
#}>i

    def _compareTo(self, obj):
        """
        (BinomialQueue, BinomialQueue) -> int

        Compares this binomial queue with the given binomial queue.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    def __iter__(self):
        """
        (BinomialQueue) -> iterator

        Returns an iterator that enumerates the elements of this binomial queue.
        """
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "BinomialQueue test program."
        print BinomialQueue.main.__doc__
        pqueue = BinomialQueue()
        PriorityQueue.test(pqueue)
        return 0
Пример #27
0
class GeneralTree(Tree):
    """
    A general tree implemented using a linked list of subtrees.
    """

#}@head

#{
    # ...
#}@tail

#{
    def __init__(self, key):
        """
        (GeneralTree, Object) -> None
        Constructs a general tree with the given object at its root.
        """
        super(GeneralTree, self).__init__()
        self._key = key
        self._degree = 0
        self._list = LinkedList()

    def purge(self):
        """
        (GeneralTree) -> None
        Purges this general tree.
        """
        self._list.purge()
        self._degree = 0
#}>a

    def getIsEmpty(self):
        """
        (GeneralTree) -> bool
        Returns false always.
        """
        return False

    def getIsLeaf(self):
        """
        (GeneralTree) -> bool
        Returns true if this general tree is a leaf.
        """
        return self._degree == 0

    def getDegree(self):
        """
        (GeneralTree) -> int
        Returns the degree of this general tree node.
        """
        return self._degree

#{
    def getKey(self):
        """
        (GeneralTree) -> Object
        Returns the key in this general tree node.
        """
        return self._key

    def getSubtree(self, i):
        """
        (GeneralTree) -> Object
        Returns the specified subtree of this general tree node.
        """
        if i < 0 or i >= self._degree:
            raise IndexError
        ptr = self._list.head
        for j in xrange(i):
            ptr = ptr.next
        return ptr.datum

    def attachSubtree(self, t):
        """
        (GeneralTree, GeneralTree) -> None
        Attaches the given general tree as a subtree
        of this general tree node.
        """
        self._list.append(t)
        self._degree += 1

    def detachSubtree(self, t):
        """
        (GeneralTree, GeneralTree) -> GeneralTree
        Detaches and returns specified general tree
        from this general tree node.
        """
        self._list.extract(t)
        self._degree -= 1
        return t
#}>b

    def _compareTo(self, obj):
        """
        (GeneralTree, GeneralTree) -> int

        Compares this general tree with the given general tree.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "GeneralTree test program."
        print GeneralTree.main.__doc__
        gt = GeneralTree('A')
        gt.attachSubtree(GeneralTree('B'))
        gt.attachSubtree(GeneralTree('C'))
        gt.attachSubtree(GeneralTree('D'))
        gt.attachSubtree(GeneralTree('E'))
        Tree.test(gt)
        return 0
Пример #28
0
class GeneralTree(Tree):
    """
    A general tree implemented using a linked list of subtrees.
    """

    #}@head

    #{
    # ...
    #}@tail

    #{
    def __init__(self, key):
        """
        (GeneralTree, Object) -> None
        Constructs a general tree with the given object at its root.
        """
        super(GeneralTree, self).__init__()
        self._key = key
        self._degree = 0
        self._list = LinkedList()

    def purge(self):
        """
        (GeneralTree) -> None
        Purges this general tree.
        """
        self._list.purge()
        self._degree = 0
#}>a

    def getIsEmpty(self):
        """
        (GeneralTree) -> bool
        Returns false always.
        """
        return False

    def getIsLeaf(self):
        """
        (GeneralTree) -> bool
        Returns true if this general tree is a leaf.
        """
        return self._degree == 0

    def getDegree(self):
        """
        (GeneralTree) -> int
        Returns the degree of this general tree node.
        """
        return self._degree

#{

    def getKey(self):
        """
        (GeneralTree) -> Object
        Returns the key in this general tree node.
        """
        return self._key

    def getSubtree(self, i):
        """
        (GeneralTree) -> Object
        Returns the specified subtree of this general tree node.
        """
        if i < 0 or i >= self._degree:
            raise IndexError
        ptr = self._list.head
        for j in xrange(i):
            ptr = ptr.next
        return ptr.datum

    def attachSubtree(self, t):
        """
        (GeneralTree, GeneralTree) -> None
        Attaches the given general tree as a subtree
        of this general tree node.
        """
        self._list.append(t)
        self._degree += 1

    def detachSubtree(self, t):
        """
        (GeneralTree, GeneralTree) -> GeneralTree
        Detaches and returns specified general tree
        from this general tree node.
        """
        self._list.extract(t)
        self._degree -= 1
        return t


#}>b

    def _compareTo(self, obj):
        """
        (GeneralTree, GeneralTree) -> int

        Compares this general tree with the given general tree.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "GeneralTree test program."
        print GeneralTree.main.__doc__
        gt = GeneralTree('A')
        gt.attachSubtree(GeneralTree('B'))
        gt.attachSubtree(GeneralTree('C'))
        gt.attachSubtree(GeneralTree('D'))
        gt.attachSubtree(GeneralTree('E'))
        Tree.test(gt)
        return 0
Пример #29
0
 def __init__(self):
   self._list = LinkedList()
Пример #30
0
class StackAsLinkedList(Stack):
    """
    Stack implemented using a linked list.
    """

#}@head

#{

    # ...
#}@tail

#{
    def __init__(self):
        """
        (StackAsLinkedList)
        Constructs a stack.
        """
        super(StackAsLinkedList, self).__init__()
        self._list = LinkedList()

    def purge(self):
        """
        (StackAsLinkedList) -> None
        Purges this stack.
        """
        self._list.purge()
        self._count = 0
#}>a

#{
    def push(self, obj):
        """
        (StackAsLinkedList, Object) -> None
        Pushes the given object on to this stack.
        """
        self._list.prepend(obj)
        self._count += 1

    def pop(self):
        """
        (StackAsLinkedList) -> None
        Pops the top object off this stack.
        """
        if self._count == 0:
            raise ContainerEmpty
        result = self._list.first
        self._list.extract(result)
        self._count -= 1
        return result

    def getTop(self):
        """
        (StackAsLinkedList) -> None
        Returns the object at the top of this stack.
        """
        if self._count == 0:
            raise ContainerEmpty
        return self._list.first
#}>b

#{
    def accept(self, visitor):
        """
        (StackAsLinkedList, Visitor) -> None
        Makes the given visitor visit all the objects in this stack.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._list.head
        while ptr is not None:
            visitor.visit(ptr.datum)
            if visitor.isDone:
                return
            ptr = ptr.next
#}>c

#{
    class Iterator(Iterator):
        """
        Enumerates the elements of a StackAsLinkedList.
        """

        def __init__(self, stack):
            """
            (StackAsLinkedList.Iterator, StackAsLinkedList) -> None
            Constructs an iterator for the given stack.
            """
            super(StackAsLinkedList.Iterator, self).__init__(
		stack)
            self._position = stack._list.head

        def next(self):
            """
            (StackAsLinkedList.Iterator) -> Object
            Returns the next element.
            """
            if self._position is None:
		raise StopIteration
	    element = self._position
	    self._position = self._position.next
            return element.datum

    def __iter__(self):
        """
        (StackAsLinkedList) -> StackAsLinkedList.Iterator
        Returns an iterator for this stack.
        """
        return self.Iterator(self)
#}>d
    
    def _compareTo(self, obj):
        """
        (StackAsLinkedList, StackAsLinkedList) -> int

        Compares this stack with the given stack.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "StackAsLinkedList test program."
        print StackAsLinkedList.main.__doc__
        stack2 = StackAsLinkedList()
        Stack.test(stack2)
        return 0
Пример #31
0
class MultisetAsLinkedList(Multiset):
    """
    Multiset implemented using a linked list of elements.
    """

    #}@head

    #{

    # ...
    #}@tail

    #{
    def __init__(self, n):
        """
        (MultisetAsLinkedList, int) -> None
        Constructs a multiset with the given universe size.
        """
        super(MultisetAsLinkedList, self).__init__(n)
        self._list = LinkedList()
#}>a

    def insert(self, item):
        """
        (MultisetAsLinkedList, Object) -> None
        Inserts the given element into this multiset.
        """
        ptr = self._list.head
        prevPtr = None
        while ptr is not None:
            if ptr.datum >= item:
                break
            prevPtr = ptr
            ptr = ptr.__next__
        if prevPtr is None:
            self._list.prepend(item)
        else:
            prevPtr.insertAfter(item)

    def withdraw(self, item):
        """
        (MultisetAsLinkedList, Object) -> None
        Withdraws the given element from this multiset.
        """
        ptr = self._list.head
        while ptr is not None:
            if ptr.datum == item:
                list.extract(ptr)
                return
            ptr = ptr.__next__

    def __contains__(self, item):
        """
        (MultisetAsLinkedList, Object) -> bool
        Returns true if the given elements is in this multiset.
        """
        ptr = self._list.head
        while ptr is not None:
            if ptr.datum == item:
                return True
            ptr = ptr.__next__
        return False

    def purge(self):
        """
        (MultisetAsLinkedList) -> None
        Purges this multiset.
        """
        self._list = LinkedList()

    def getCount(self):
        """
        (MultisetAsLinkedList) -> int
        Returns the number of elements in this multiset.
        """
        result = 0
        ptr = self._list.head
        while ptr is not None:
            result += 1
            ptr = ptr.__next__
        return result

    def accept(self, visitor):
        """
        (MultisetAsLinkedList, Visitor) -> None
        Makes the given visitor visit all the elements in this multiset.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._list.head
        while ptr is not None:
            visitor.visit(ptr.datum)
            if visitor.isDone:
                return
            ptr = ptr.__next__

#{

    def __or__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> MultisetAsLinkedList
        Returns the union of this multiset and the given multiset.
        """
        assert isinstance(set, MultisetAsLinkedList)
        assert self._universeSize == set._universeSize
        result = MultisetAsLinkedList(self._universeSize)
        p = self._list.head
        q = set._list.head
        while p is not None and q is not None:
            if p.datum <= q.datum:
                result._list.append(p.datum)
                p = p.__next__
            else:
                result._list.append(q.datum)
                q = q.__next__
        while p is not None:
            result._list.append(p.datum)
            p = p.__next__
        while q is not None:
            result._list.append(q.datum)
            q = q.__next__
        return result
#}>b

#{

    def __and__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> MultisetAsLinkedList
        Returns the intersection of this multiset and the given multiset.
        """
        assert isinstance(set, MultisetAsLinkedList)
        assert self._universeSize == set._universeSize
        result = MultisetAsLinkedList(self._universeSize)
        p = self._list.head
        q = set._list.head
        while p is not None and q is not None:
            diff = p.datum - q.datum
            if diff == 0:
                result._list.append(p.datum)
            if diff <= 0:
                p = p.__next__
            if diff >= 0:
                q = q.__next__
        return result


#}>c

    def __sub__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> MultisetAsLinkedList
        Returns the difference of this multiset and the given multiset.
        """
        assert isinstance(set, MultisetAsLinkedList)
        assert self._universeSize == set._universeSize
        result = MultisetAsLinkedList(self._universeSize)
        p = self._list.head
        q = set._list.head
        while p is not None and q is not None:
            diff = p.datum - q.datum
            if diff < 0:
                result._list.append(p.datum)
            if diff <= 0:
                p = p.__next__
            if diff >= 0:
                q = q.__next__
        while p is not None:
            result._list.append(p.datum)
            p = p.__next__
        return result

    def __le__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> bool
        Returns true if this multiset is a proper subset of the given multiset.
        """
        assert isinstance(set, MultisetAsLinkedList)
        assert self._universeSize == set._universeSize
        p = self_list.head
        q = set._list.head
        while p is not None and q is not None:
            diff = p.datum - q.datum
            if diff == 0:
                p = p.__next__
                q = q.__next__
            elif diff > 0:
                q = q.__next__
            else:
                return False
        if p is not None:
            return False
        else:
            return True

    def __eq__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> bool
        Returns true if this multiset is equal to the given multiset.
        """
        assert isinstance(set, MultisetAsLinkedList)
        assert self._universeSize == set._universeSize
        p = self._list.head
        q = set._list.head
        while p is not None and q is not None:
            if p.datum != q.datum:
                return False
            p = p.__next__
            q = q.__next__
        if p is not None or q is not None:
            return False
        else:
            return True

    class Iterator(Iterator):
        """
        Enumerates the elements of a MultisetAsLinkedList.
        """

        def __init__(self, multiset):
            """
            (MultisetAsLinkedList.Iterator, MultisetAsLinkedList) -> None
            Constructs an interator for the given multiset.
            """
            super(MultisetAsLinkedList.Iterator, self).__init__(multiset)
            self._ptr = None

        def __next__(self):
            """
            (MultisetAsLinkedList.Iterator) -> Object
            Returns the next element in the multiset.
            """
            if self._ptr is None:
                self._ptr = self._container._list.head
            else:
                self._ptr = self._ptr.__next__
            if self._ptr == None:
                raise StopIteration
            return self._ptr.datum

    def __iter__(self):
        """
        (MultisetAsLinkedList) -> MultisetAsLinkedList.Iterator
        Returns an iterator for this multiset.
        """
        return self.Iterator(self)

    def _compareTo(self, obj):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> int

        Compares this multiset with the given multiset.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "MultisetAsLinkedList test program."
        print((MultisetAsLinkedList.main.__doc__))
        Multiset.test(MultisetAsLinkedList(32), \
            MultisetAsLinkedList(32), MultisetAsLinkedList(32))
        return 0
Пример #32
0
class OrderedListAsLinkedList(OrderedList):
    """
    Ordered list implemented using a linked list.
    """

#}@head

#{

    # ...
#}@tail

#{
    def __init__(self):
        """
        (OrderedListAsLinkedList) -> None
        Constructs an ordered list.
        """
        super(OrderedListAsLinkedList, self).__init__()
        self._linkedList = LinkedList()
#}>a

#{
    def insert(self, obj):
        """
        (OrderedListAsLinkedList, Object) -> None
        Inserts the given object at the end of this list.
        """
        self._linkedList.append(obj)
        self._count += 1

    def __getitem__(self, offset):
        """
        (OrderedListAsLinkedList, int) -> Object
        Returns the object in this list at the given offset.
        """
        if offset < 0 or offset >= self._count:
            raise IndexError
        ptr = self._linkedList.head
        i = 0
        while i < offset and ptr is not None:
            ptr = ptr.next
            i += 1
        return ptr.datum
#}>b

    def purge(self):
        """
        (OrderedListAsLinkedList) -> None
        Purges this ordered list.
        """
        self._linkedList = LinkedList()
        self._count = 0

    def accept(self, visitor):
        """
        (OrderedListAsLinkedList, Visitor) -> None
        Makes the given visitor visit all the objects in this ordered list.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._linkedList.head
        while ptr is not None:
            visitor.visit(ptr.datum)
            if visitor.isDone:
                return
            ptr = ptr.next

#{
    def __contains__(self, obj):
        """
        (OrderedListAsLinkedList, Object) -> bool
        Returns true if the given object instance is in this ordered list.
        """
        ptr = self._linkedList.head
        while ptr is not None:
            if ptr.datum is obj:
                return True
            ptr = ptr.next
        return False

    def find(self, arg):
        """
        (OrderedListAsLinkedList, Object) -> Object
        Finds an object in this ordered list that equals the given object.
        """
        ptr = self._linkedList.head
        while ptr is not None:
            obj = ptr.datum
            if obj == arg:
                return obj
            ptr = ptr.next
        return None
#}>c

#{
    def withdraw(self, obj):
        """
        (OrderedListAsLinkedList, Object) -> None
        Withdraws the given object instance from this ordered list.
        """
        if self._count == 0:
            raise ContainerEmpty
        self._linkedList.extract(obj)
        self._count -= 1
#}>d

#{
    def findPosition(self, obj):
        """
        (OrderedListAsLinkedList, Object) -> OrderedListAsLinkedList.Cursor
        Finds the position of an object in this list
        that equals the given object and returns a cursor
        that refers to that object.
        """
        ptr = self._linkedList.head
        while ptr is not None:
            if ptr.datum == obj:
                break
            ptr = ptr.next
        return self.Cursor(self, ptr)
#}>e

#{
    class Cursor(Cursor):
        """
        A cursor that refers to an object in an ordered list.
        """

#}@head

#{

        # ...
#}@tail

#{
        def __init__(self, list, element):
            """
            (OrderedListAsLinkedList.Cursor, OrderedListAsLinkedList, 
                LinkedList.Element) -> None
            Constructs a cursor that refers to the object
           in the given element of the given list.
           """
	    super(OrderedListAsLinkedList.Cursor, self) \
		.__init__(list)
            self._element = element

        def getDatum(self):
            """
            (OrderedListAsLinkedList.Cursor) -> Object
            Returns the object to which this cursor refers.
            """
            return self._element.datum
#}>h

#{
        def insertAfter(self, obj):
            """
            (OrderedListAsLinkedList.Cursor, Object) -> None
            Inserts the given object into the list
            after the object to which this cursor refers.
            """
            self._element.insertAfter(obj)
            self._list._count += 1
#}>f

        def insertBefore(self, obj):
            """
            (OrderedListAsLinkedList.Cursor, Object) -> None
            Inserts the given object into the list
            before the object to which this cursor refers.
            """
            self._element.insertBefore(obj)
            self._list._count += 1

#{
        def withdraw(self):
            """
            (OrderedListAsLinkedList.Cursor) -> None
            Withdraws from the list the object to which this cursor refers.
            """
            self._list._linkedList.extract(self._element.datum)
            self._list._count -= 1
#}>g

    class Iterator(Iterator):
        """
        Enumerates the items in an ordered list.
        """

        def __init__(self, list):
            """
            (OrderedListAsLinkedList.Iterator, OrderedListAsLinkedList) -> None
            Constructs an iterator for the given list.
            """
            super(OrderedListAsLinkedList.Iterator, self).__init__(list)
            self._element = None

        def next(self):
            """
            (OrderedListAsLinkedList.Iterator) -> Object
            Returns the next element.
            """
            if self._element is None:
                self._element = self._container._linkedList.head
            else:
                self._element = self._element.next
            if self._element is None:
                raise StopIteration
            return self._element.datum

    def __iter__(self):
        """
        (OrderedListAsLinkedList) -> OrderedListAsLinkedList.Iterator
        Returns an iterator for this ordered list.
        """
        return self.Iterator(self)

    def _compareTo(self, obj):
        """
        (OrderedListAsLinkedList, OrderedListAsLinkedList) -> int

        Compares this ordered list with the given ordered list.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    def main(*argv):
        "OrderedListAsLinkedList test program."
        print OrderedListAsLinkedList.main.__doc__
        list = OrderedListAsLinkedList()
        OrderedList.test(list)
        return 0
    main = staticmethod(main)
Пример #33
0
 def purge(self):
     """
     (MultisetAsLinkedList) -> None
     Purges this multiset.
     """
     self._list = LinkedList()
Пример #34
0
class OrderedListAsLinkedList(OrderedList):
    """
    Ordered list implemented using a linked list.
    """

#}@head

#{

    # ...
#}@tail

#{
    def __init__(self):
        """
        (OrderedListAsLinkedList) -> None
        Constructs an ordered list.
        """
        super(OrderedListAsLinkedList, self).__init__()
        self._linkedList = LinkedList()
#}>a

#{
    def insert(self, obj):
        """
        (OrderedListAsLinkedList, Object) -> None
        Inserts the given object at the end of this list.
        """
        self._linkedList.append(obj)
        self._count += 1

    def __getitem__(self, offset):
        """
        (OrderedListAsLinkedList, int) -> Object
        Returns the object in this list at the given offset.
        """
        if offset < 0 or offset >= self._count:
            raise IndexError
        ptr = self._linkedList.head
        i = 0
        while i < offset and ptr is not None:
            ptr = ptr.next
            i += 1
        return ptr.datum
#}>b

    def purge(self):
        """
        (OrderedListAsLinkedList) -> None
        Purges this ordered list.
        """
        self._linkedList = LinkedList()
        self._count = 0

    def accept(self, visitor):
        """
        (OrderedListAsLinkedList, Visitor) -> None
        Makes the given visitor visit all the objects in this ordered list.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._linkedList.head
        while ptr is not None:
            visitor.visit(ptr.datum)
            if visitor.isDone:
                return
            ptr = ptr.next

#{
    def __contains__(self, obj):
        """
        (OrderedListAsLinkedList, Object) -> bool
        Returns true if the given object instance is in this ordered list.
        """
        ptr = self._linkedList.head
        while ptr is not None:
            if ptr.datum is obj:
                return True
            ptr = ptr.next
        return False

    def find(self, arg):
        """
        (OrderedListAsLinkedList, Object) -> Object
        Finds an object in this ordered list that equals the given object.
        """
        ptr = self._linkedList.head
        while ptr is not None:
            obj = ptr.datum
            if obj == arg:
                return obj
            ptr = ptr.next
        return None
#}>c

#{
    def withdraw(self, obj):
        """
        (OrderedListAsLinkedList, Object) -> None
        Withdraws the given object instance from this ordered list.
        """
        if self._count == 0:
            raise ContainerEmpty
        self._linkedList.extract(obj)
        self._count -= 1
#}>d

#{
    def findPosition(self, obj):
        """
        (OrderedListAsLinkedList, Object) -> OrderedListAsLinkedList.Cursor
        Finds the position of an object in this list
        that equals the given object and returns a cursor
        that refers to that object.
        """
        ptr = self._linkedList.head
        while ptr is not None:
            if ptr.datum == obj:
                break
            ptr = ptr.next
        return self.Cursor(self, ptr)
#}>e

#{
    class Cursor(Cursor):
        """
        A cursor that refers to an object in an ordered list.
        """

#}@head

#{

        # ...
#}@tail

#{
        def __init__(self, list, element):
            """
            (OrderedListAsLinkedList.Cursor, OrderedListAsLinkedList, 
                LinkedList.Element) -> None
            Constructs a cursor that refers to the object
           in the given element of the given list.
           """
	    super(OrderedListAsLinkedList.Cursor, self) \
		.__init__(list)
            self._element = element

        def getDatum(self):
            """
            (OrderedListAsLinkedList.Cursor) -> Object
            Returns the object to which this cursor refers.
            """
            return self._element.datum
#}>h

#{
        def insertAfter(self, obj):
            """
            (OrderedListAsLinkedList.Cursor, Object) -> None
            Inserts the given object into the list
            after the object to which this cursor refers.
            """
            self._element.insertAfter(obj)
            self._list._count += 1
#}>f

        def insertBefore(self, obj):
            """
            (OrderedListAsLinkedList.Cursor, Object) -> None
            Inserts the given object into the list
            before the object to which this cursor refers.
            """
            self._element.insertBefore(obj)
            self._list._count += 1

#{
        def withdraw(self):
            """
            (OrderedListAsLinkedList.Cursor) -> None
            Withdraws from the list the object to which this cursor refers.
            """
            self._list._linkedList.extract(self._element.datum)
            self._list._count -= 1
#}>g

    class Iterator(Iterator):
        """
        Enumerates the items in an ordered list.
        """

        def __init__(self, list):
            """
            (OrderedListAsLinkedList.Iterator, OrderedListAsLinkedList) -> None
            Constructs an iterator for the given list.
            """
            super(OrderedListAsLinkedList.Iterator, self).__init__(list)
            self._element = None

        def next(self):
            """
            (OrderedListAsLinkedList.Iterator) -> Object
            Returns the next element.
            """
            if self._element is None:
                self._element = self._container._linkedList.head
            else:
                self._element = self._element.next
            if self._element is None:
                raise StopIteration
            return self._element.datum

    def __iter__(self):
        """
        (OrderedListAsLinkedList) -> OrderedListAsLinkedList.Iterator
        Returns an iterator for this ordered list.
        """
        return self.Iterator(self)

    def _compareTo(self, obj):
        """
        (OrderedListAsLinkedList, OrderedListAsLinkedList) -> int

        Compares this ordered list with the given ordered list.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "OrderedListAsLinkedList test program."
        print OrderedListAsLinkedList.main.__doc__
        list = OrderedListAsLinkedList()
        OrderedList.test(list)
        return 0
Пример #35
0
class BinomialQueue(MergeablePriorityQueue):
    """
    Mergeable priority queue implemented as a binomial queue.
    """

    #}@head

    #{

    # ...
    #}@tail

    #{
    def __init__(self, *args):
        """
        (BinomialQueue, ...) -> None
        Constructor.
        """
        super(BinomialQueue, self).__init__()
        self._treeList = LinkedList()
        if len(args) == 0:
            pass
        elif len(args) == 1:
            assert isinstance(args[0], self.BinomialTree)
            self._treeList.append(args[0])
        else:
            raise ValueError
#}>a

#{

    def addTree(self, tree):
        """
        (BinomialQueue, BinomialQueue.BinomialTree) -> None
        Adds the given binomial tree to this binomial queue.
        """
        self._treeList.append(tree)
        self._count += tree.count

    def removeTree(self, tree):
        """
        (BinomialQueue, BinomialQueue.BinomialTree) -> None
        Removes the given binomial tree from this binomial queue.
        """
        self._treeList.extract(tree)
        self._count -= tree.count
#}>b

    def purge(self):
        """
        (BinomialQueue) -> None
        Purges this binomial queue.
        """
        self._treeList = LinkedList()
        self._count = 0

    def accept(self, visitor):
        """
        (BinomialQueue, Visitor) -> None
        Makes the given visitor visit the elements of this binomial queue.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._treeList.head
        while ptr is not None:
            tree = ptr.datum
            tree.depthFirstTraversal(PreOrder(visitor))
            ptr = ptr.__next__

#{

    def getMinTree(self):
        """
        (BinomialQueue) -> BinomialQueue.BinomialTree
        Returns the binomial tree in this binomial queue
        with the smallest root.
        """
        minTree = None
        ptr = self._treeList.head
        while ptr is not None:
            tree = ptr.datum
            if minTree is None or tree.key < minTree.key:
                minTree = tree
            ptr = ptr.__next__
        return minTree

    minTree = property(fget=lambda self: self.getMinTree())

    def getMin(self):
        """
        (BinomialQueue) -> Object
        Returns the object in this binomial queue with the smallest value.
        """
        if self._count == 0:
            raise ContainerEmpty
        return self.minTree.key
#}>c

#{

    def merge(self, queue):
        """
        (BinomialQueue, BinomialQueue) -> None
        Merges the contents of the given binomial queue
        with this binomial queue.
        """
        oldList = self._treeList
        self._treeList = LinkedList()
        self._count = 0
        p = oldList.head
        q = queue._treeList.head
        carry = None
        i = 0
        while p is not None or q is not None \
                or carry is not None:
            a = None
            if p is not None:
                tree = p.datum
                if tree.degree == i:
                    a = tree
                    p = p.__next__
            b = None
            if q is not None:
                tree = q.datum
                if tree.degree == i:
                    b = tree
                    q = q.__next__
            (sum, carry) = BinomialQueue.fullAdder(a, b, carry)
            if sum is not None:
                self.addTree(sum)
            i += 1
        queue.purge()
#}>d

#{

    @staticmethod
    def fullAdder(a, b, c):
        """
        (BinomialTree, BinomialTree, BinomialTree) ->
	    (BinomialTree, BinomialTree)
        Returns the (sum, carry) of the given binomial trees.
	"""
        if a is None:
            if b is None:
                if c is None:
                    return (None, None)
                else:
                    return (c, None)
            else:
                if c is None:
                    return (b, None)
                else:
                    return (None, b.add(c))
        else:
            if b is None:
                if c is None:
                    return (a, None)
                else:
                    return (None, a.add(c))
            else:
                if c is None:
                    return (None, a.add(b))
                else:
                    return (c, a.add(b))
#}>e

#{

    def enqueue(self, obj):
        """
        (BinomialQueue, Object) -> None
        Enqueues the given object in this binomial queue.
        """
        self.merge(BinomialQueue(BinomialQueue.BinomialTree(obj)))
#}>f

#{

    def dequeueMin(self):
        """
        (BinomialQueue) -> Object
        Dequeues and returns the object in this binomial queue
        with the smallest value.
        """
        if self._count == 0:
            raise ContainerEmpty
        minTree = self.minTree
        self.removeTree(minTree)
        queue = BinomialQueue()
        while minTree.degree > 0:
            child = minTree.getSubtree(0)
            minTree.detachSubtree(child)
            queue.addTree(child)
        self.merge(queue)
        return minTree.key
#}>g

    def __str__(self):
        """
        (BinomialQueue) -> str
        Returns a string representation of this binomial queue.
        """
        result = self.__class__.__name__ + " {\n"
        ptr = self._treeList.head
        while ptr is not None:
            result = result + str(ptr.datum) + "\n"
            ptr = ptr.__next__
        result = result + "}"
        return result

#{

    class BinomialTree(GeneralTree):
        """
        A binomial tree implemented as a general tree.
        """

        #}@head

        #{

        # ...
        #}@tail

        #{
        def __init__(self, key):
            """
            (BinomialQueue.BinomialTree, Object) -> None
            Constructor.
            """
            super(BinomialQueue.BinomialTree, self).__init__(key)
#}>h

        def getCount(self):
            """
            (BinomialQueue.BinomialTree) -> int
            Returns the number of objects in this binomial tree.
            """
            return 1 << self._degree

        def swapContentsWith(self, tree):
            """
            (BinomialQueue.BinomialTree, BinomialQueue.BinomialTree) -> None
            Swaps the contents of this binomial tree
            with the given binomial tree.
            """
            tmp = self._key
            self._key = tree._key
            tree._key = tmp
            tmp = self._list
            self._list = tree._list
            tree._list = tmp
            tmp = self._degree
            self._degree = tree._degree
            tree._degree = tmp

#{

        def add(self, tree):
            """
            (BinomialQueue.BinomialTree, BinomialQueue.BinomialTree) ->
                BinomialQueue.BinomialTree
            Adds this binomail tree and the given binomial tree.
            """
            if self._degree != tree._degree:
                raise ValueError
            if self._key > tree._key:
                self.swapContentsWith(tree)
            self.attachSubtree(tree)
            return self


#}>i

    def _compareTo(self, obj):
        """
        (BinomialQueue, BinomialQueue) -> int

        Compares this binomial queue with the given binomial queue.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    def __iter__(self):
        """
        (BinomialQueue) -> iterator

        Returns an iterator that enumerates the elements of this binomial queue.
        """
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "BinomialQueue test program."
        print((BinomialQueue.main.__doc__))
        pqueue = BinomialQueue()
        PriorityQueue.test(pqueue)
        return 0
class MultisetAsLinkedList(Multiset):
    """
    Multiset implemented using a linked list of elements.
    """

#}@head

#{

    # ...
#}@tail

#{
    def __init__(self, n):
        """
        (MultisetAsLinkedList, int) -> None
        Constructs a multiset with the given universe size.
        """
        super(MultisetAsLinkedList, self).__init__(n)
        self._list = LinkedList()
#}>a

    def insert(self, item):
        """
        (MultisetAsLinkedList, Object) -> None
        Inserts the given element into this multiset.
        """
        ptr = self._list.head
        prevPtr = None
        while ptr is not None:
            if ptr.datum >= item:
                break
            prevPtr = ptr
            ptr = ptr.next
        if prevPtr is None:
            self._list.prepend(item)
        else:
            prevPtr.insertAfter(item)

    def withdraw(self, item):
        """
        (MultisetAsLinkedList, Object) -> None
        Withdraws the given element from this multiset.
        """
        ptr = self._list.head
        while ptr is not None:
            if ptr.datum == item:
                list.extract(ptr)
                return
            ptr = ptr.next

    def __contains__(self, item):
        """
        (MultisetAsLinkedList, Object) -> bool
        Returns true if the given elements is in this multiset.
        """
        ptr = self._list.head
        while ptr is not None:
            if ptr.datum == item:
                return True
            ptr = ptr.next
        return False

    def purge(self):
        """
        (MultisetAsLinkedList) -> None
        Purges this multiset.
        """
        self._list = LinkedList()

    def getCount(self):
        """
        (MultisetAsLinkedList) -> int
        Returns the number of elements in this multiset.
        """
        result = 0
        ptr = self._list.head
        while ptr is not None:
            result += 1
            ptr = ptr.next
        return result

    def accept(self, visitor):
        """
        (MultisetAsLinkedList, Visitor) -> None
        Makes the given visitor visit all the elements in this multiset.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._list.head
        while ptr is not None:
            visitor.visit(ptr.datum)
            if visitor.isDone:
                return
            ptr = ptr.next

#{
    def __or__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> MultisetAsLinkedList
        Returns the union of this multiset and the given multiset.
        """
	assert isinstance(set, MultisetAsLinkedList)
	assert self._universeSize == set._universeSize
        result = MultisetAsLinkedList(self._universeSize)
        p = self._list.head
        q = set._list.head
        while p is not None and q is not None:
            if p.datum <= q.datum:
                result._list.append(p.datum)
                p = p.next
            else:
                result._list.append(q.datum)
                q = q.next
        while p is not None:
            result._list.append(p.datum)
            p = p.next
        while q is not None:
            result._list.append(q.datum)
            q = q.next
        return result
#}>b

#{
    def __and__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> MultisetAsLinkedList
        Returns the intersection of this multiset and the given multiset.
        """
	assert isinstance(set, MultisetAsLinkedList)
	assert self._universeSize == set._universeSize
        result = MultisetAsLinkedList(self._universeSize)
        p = self._list.head
        q = set._list.head
        while p is not None and q is not None:
            diff = p.datum - q.datum
            if diff == 0:
                result._list.append(p.datum)
            if diff <= 0:
                p = p.next
            if diff >= 0:
                q = q.next
        return result
#}>c

    def __sub__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> MultisetAsLinkedList
        Returns the difference of this multiset and the given multiset.
        """
	assert isinstance(set, MultisetAsLinkedList)
	assert self._universeSize == set._universeSize
        result = MultisetAsLinkedList(self._universeSize)
        p = self._list.head
        q = set._list.head
        while p is not None and q is not None:
            diff = p.datum - q.datum
            if diff < 0:
                result._list.append(p.datum)
            if diff <= 0:
                p = p.next
            if diff >= 0:
                q = q.next
        while p is not None:
            result._list.append(p.datum)
            p = p.next
        return result

    def __le__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> bool
        Returns true if this multiset is a proper subset of the given multiset.
        """
	assert isinstance(set, MultisetAsLinkedList)
	assert self._universeSize == set._universeSize
        p = self_list.head
        q = set._list.head
        while p is not None and q is not None:
            diff = p.datum - q.datum
            if diff == 0:
                p = p.next
                q = q.next
            elif diff > 0:
                q = q.next
            else:
                return False
        if p is not None:
            return False
        else:
            return True

    def __eq__(self, set):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> bool
        Returns true if this multiset is equal to the given multiset.
        """
	assert isinstance(set, MultisetAsLinkedList)
	assert self._universeSize == set._universeSize
        p = self._list.head
        q = set._list.head
        while p is not None and q is not None:
            if p.datum != q.datum:
                return False
            p = p.next
            q = q.next
        if p is not None or q is not None:
            return False
        else:
            return True

    class Iterator(Iterator):
        """
        Enumerates the elements of a MultisetAsLinkedList.
        """

        def __init__(self, multiset):
            """
            (MultisetAsLinkedList.Iterator, MultisetAsLinkedList) -> None
            Constructs an interator for the given multiset.
            """
            super(MultisetAsLinkedList.Iterator, self).__init__(multiset)
            self._ptr = None

        def next(self):
            """
            (MultisetAsLinkedList.Iterator) -> Object
            Returns the next element in the multiset.
            """
            if self._ptr is None:
                self._ptr = self._container._list.head
            else:
                self._ptr = self._ptr.next
            if self._ptr == None:
                raise StopIteration
            return self._ptr.datum

    def __iter__(self):
        """
        (MultisetAsLinkedList) -> MultisetAsLinkedList.Iterator
        Returns an iterator for this multiset.
        """
        return self.Iterator(self)

    def _compareTo(self, obj):
        """
        (MultisetAsLinkedList, MultisetAsLinkedList) -> int

        Compares this multiset with the given multiset.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError


    @staticmethod
    def main(*argv):
        "MultisetAsLinkedList test program."
        print MultisetAsLinkedList.main.__doc__
        Multiset.test(MultisetAsLinkedList(32), \
            MultisetAsLinkedList(32), MultisetAsLinkedList(32))
        return 0
Пример #37
0
class QueueAsLinkedList(Queue):
    """
    Queue implemented using a linked list.
    """

    #}@head

    #{

    # ...
    #}@tail

    #{
    def __init__(self):
        """
        (QueueAsLinkedList) -> None
        Constructs a queue.
        """
        super(QueueAsLinkedList, self).__init__()
        self._list = LinkedList()

    def purge(self):
        """
        (QueueAsLinkedList) -> None
        Purges this queue.
        """
        self._list.purge()
        self._count = 0
#}>a

#{

    def getHead(self):
        """
        (QueueAsLinkedList) -> Object
        Returns the object at the head of this queue.
        """
        if self._count == 0:
            raise ContainerEmpty
        return self._list.first

    def enqueue(self, obj):
        """
        (QueueAsLinkedList, Object) -> None
        Enqueues the given object to the tail of this queue.
        """
        self._list.append(obj)
        self._count += 1

    def dequeue(self):
        """
        (QueueAsLinkedList) -> Object
        Dequeues the object at the head of this queue.
        """
        if self._count == 0:
            raise ContainerEmpty
        result = self._list.first
        self._list.extract(result)
        self._count -= 1
        return result


#}>b

    def accept(self, visitor):
        """
        (QueueAsLinkedList, Visitor) -> None
        Makes the given visitor visit all the objects in this queue.
        """
        assert isinstance(visitor, Visitor)
        ptr = self._list.head
        while ptr is not None:
            visitor.visit(ptr.datum)
            if visitor.isDone:
                return
            ptr = ptr.next

    class Iterator(Iterator):
        """
        Enumerates the elements of a QueueAsLinkedList.
        """
        def __init__(self, queue):
            """
            (QueueAsLinkedList.Iterator, QueueAsLinkedList) -> None
            Constructs an iterator for the given queue.
            """
            super(QueueAsLinkedList.Iterator).__init__(queue)
            self._position = None

        def next(self):
            """
            (QueueAsLinkedList.Iterator) -> Object
            Returns the next element.
            """
            if self._position is None:
                self._position = self._container._list.head
            else:
                self._position = self._position.next
            if self._position is None:
                raise StopIteration
            return self._position.datum

    def __iter__(self):
        """
        (QueueAsLinkedList) -> QueueAsLinkedList.Iterator
        Returns an iterator for this queue.
        """
        return self.Iterator(self)

    def _compareTo(self, obj):
        """
        (QueueAsLinkedList, QueueAsLinkedList) -> int

        Comparse this queue with the given queue.
        """
        assert isinstance(self, obj.__class__)
        raise NotImplementedError

    @staticmethod
    def main(*argv):
        "QueueAsLinkedList test program."
        print QueueAsLinkedList.main.__doc__
        queue2 = QueueAsLinkedList()
        Queue.test(queue2)
        return 0