def criticalPathAnalysis(g): """ (Digraph) -> DigraphAsLists Computes the critical path in an event-node graph. """ n = g.numberOfVertices earliestTime = Array(n) earliestTime[0] = 0 g.topologicalOrderTraversal( Algorithms.EarliestTimeVisitor(earliestTime)) latestTime = Array(n) latestTime[n - 1] = earliestTime[n - 1] g.depthFirstTraversal( PostOrder(Algorithms.LatestTimeVisitor(latestTime)), 0) slackGraph = DigraphAsLists(n) for v in range(n): slackGraph.addVertex(v) for e in g.edges: slack = latestTime[e.v1.number] - \ earliestTime[e.v0.number] - e.weight slackGraph.addEdge(e.v0.number, e.v1.number, slack) return Algorithms.DijkstrasAlgorithm(slackGraph, 0)
def __init__(self, m): """ (MWayTree, int) -> None Constructs an empty M-way tree. """ assert m > 2 super(MWayTree, self).__init__() self._key = Array(m - 1, 1) self._subtree = Array(m)
def __init__(self, *dimensions): """ (MultiDimensionalArray, Array) -> None Constructs a multi-dimensional array with the given dimensions. """ self._dimensions = Array(len(dimensions)) self._factors = Array(len(dimensions)) product = 1 i = len(dimensions) - 1 while i >= 0: self._dimensions[i] = dimensions[i] self._factors[i] = product product *= self._dimensions[i] i -= 1 self._data = Array(product)
def __init__(self, size=0): """ (StackAsArray [, int]) -> None Constructs a stack of the given size. """ super(StackAsArray, self).__init__() self._array = Array(size)
def purge(self): """ (Deap) -> None Purges this deap. """ self._array = Array(len(self_.array), 1) self._count = 0
def __init__(self, length=0): """ (Deap, int) -> None Constructs a deap with the given length. """ super(Deap, self).__init__() self._array = Array(length + 1, 1)
def __init__(self, size=0): """ (OrderedListAsArray [, int]) -> None Constructs an ordered list of the given size. """ super(OrderedListAsArray, self).__init__() self._array = Array(size)
def DijkstrasAlgorithm(g, s): """ (Digraph, int) -> DigraphAsLists Dijkstra's algorithm to solve the single-source, shortest path problem for the given edge-weighted, directed graph. """ n = g.numberOfVertices table = Array(n) for v in range(n): table[v] = Algorithms.Entry() table[s].distance = 0 queue = BinaryHeap(g.numberOfEdges) queue.enqueue(Association(0, g[s])) while not queue.isEmpty: assoc = queue.dequeueMin() v0 = assoc.value if not table[v0.number].known: table[v0.number].known = True for e in v0.emanatingEdges: v1 = e.mateOf(v0) d = table[v0.number].distance + e.weight if table[v1.number].distance > d: table[v1.number].distance = d table[v1.number].predecessor = v0.number queue.enqueue(Association(d, v1)) result = DigraphAsLists(n) for v in range(n): result.addVertex(v, table[v].distance) for v in range(n): if v != s: result.addEdge(v, table[v].predecessor) return result
def __init__(self): """ (RadixSorter) -> None Constructor. """ self._count = Array(self.R) self._tempArray = None
def PrimsAlgorithm(g, s): """ (Graph, int) -> GraphAsLists Prim's algorithm to find a minimum-cost spanning tree for the given edge-weighted, undirected graph. """ n = g.numberOfVertices table = Array(n) for v in range(n): table[v] = Algorithms.Entry() table[s].distance = 0 queue = BinaryHeap(g.numberOfEdges) queue.enqueue(Association(0, g[s])) while not queue.isEmpty: assoc = queue.dequeueMin() v0 = assoc.value if not table[v0.number].known: table[v0.number].known = True for e in v0.emanatingEdges: v1 = e.mateOf(v0) d = e.weight if not table[v1.number].known and \ table[v1.number].distance > d: table[v1.number].distance = d table[v1.number].predecessor = v0.number queue.enqueue(Association(d, v1)) result = GraphAsLists(n) for v in range(n): result.addVertex(v) for v in range(n): if v != s: result.addEdge(v, table[v].predecessor) return result
def __init__(self, length=0): """ (BinaryHeap [,int]) -> None Constructs a binary heap of the given length. """ super(BinaryHeap, self).__init__() self._array = Array(length, 1) # Base index is 1.
def test(sorter, n, seed, *args): if len(args) == 0: m = 0 elif len(args) == 1: m = args[0] else: raise ValueError RandomNumberGenerator.seed = seed data = Array(n) for i in xrange(n): datum = int(sys.maxint * RandomNumberGenerator.next) if m != 0: datum %= m data[i] = datum timer = Timer() timer.start() sorter.sort(data) timer.stop() datum = "%s %s %s %g" % (sorter.__class__.__name__, n, seed, timer.getElapsedTime()) print datum sys.stderr.write(datum + "\n") for i in xrange(1, n): if data[i] < data[i - 1]: print "FAILED" break
def __setitem__(self, indices, value): """ (SparseMatrixAsVector, (int, int), Object) -> None Sets the element of this matrix at the given indices to the given value. """ i = indices[0] j = indices[1] if i < 0 or i >= self._numberOfRows: raise IndexError if j < 0 or j >= self._numberOfColumns: raise IndexError position = self.findPosition(i, j) if position >= 0: self._array[position]._datum = value else: if len(self._array) == self._numberOfElements: newArray = Array(2 * len(self._array)) for p in xrange(len(self._array)): newArray[p] = self._array[p] for p in xrange(len(self._array), len(newArray)): newArray[p] = self.Entry() self._array = newArray k = self._numberOfElements while k > 0 and (self._array[k - 1]._row > i or \ self._array[k - 1]._row == i and \ self._array[k - 1]._column >= j): self._array[k] = self._array[k - 1] k -= 1 self._array[k] = self.Entry(i, j, value) self._numberOfElements += 1
def getTranspose(self): """ (SparseMatrixAsVector) -> SparseMatrixAsVector Returns the transpose of this matrix. """ result = SparseMatrixAsVector(self._numberOfColumns, self._numberOfRows, self._numberOfElements) offset = Array(self._numberOfColumns) for i in xrange(self._numberOfColumns): offset[i] = 0 for i in xrange(self._numberOfElements): offset[self._array[i]._column] += 1 sum = 0 for i in xrange(self._numberOfColumns): tmp = offset[i] offset[i] = sum sum += tmp for i in xrange(self._numberOfElements): result._array[offset[self._array[i]._column]] = \ self.Entry(self._array[i]._column, self._array[i]._row, self._array[i]._datum) offset[self._array[i]._column] += 1 result._numberOfElements = self._numberOfElements return result
def _sort(self): """ (TwoWayMergeSorter) -> None Sorts the elements of the array. """ self._tempArray = Array(self._n) self.mergesort(0, self._n - 1) self._tempArray = None
def __init__(self, m): """ (BucketSorter, int) -> None Constructs a bucket sorter with the given number of buckets. """ super(BucketSorter, self).__init__() self._m = m self._count = Array(self._m)
def __init__(self, length): """ (ChainedScatterTable, int) -> None Constructs a chained scatter table with the given length. """ super(ChainedScatterTable, self).__init__() self._array = Array(length) for i in xrange(len(self._array)): self._array[i] = self.Entry(None, self.NULL)
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()
def __init__(self, size=0): """ (QueueAsArray [, int]) -> None Constructs a queue of the given size. """ super(QueueAsArray, self).__init__() self._array = Array(size) self._head = 0 self._tail = size - 1
def __init__(self, length): """ (OpenScatterTable, int) -> None Constructs an open scatter table of the given length. """ super(OpenScatterTable, self).__init__() self._array = Array(length) for i in range(len(self._array)): self._array[i] = self.Entry(self.EMPTY, None)
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()
def __init__(self, n): """ (SetAsBitVector, int) -> None Constructs a set with the given universe size. """ super(SetAsBitVector, self).__init__(n) self._vector = Array((n + self.BITS - 1) / self.BITS) for i in xrange(len(self._vector)): self._vector[i] = 0
def __init__(self, n): """ (MultisetAsArray, int) -> None Constructs a multiset with the given universe size. """ super(MultisetAsArray, self).__init__(n) self._array = Array(self._universeSize) for item in range(self._universeSize): self._array[item] = 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()
def __init__(self, n): """ (PartitionAsForest, int) -> None Constructs a partition with the given universe size. """ super(PartitionAsForest, self).__init__(n) self._array = Array(self._universeSize) for item in range(self._universeSize): self._array[item] = self.PartitionTree(self, item) self._count = self._universeSize
def __init__(self, size): """ (Graph, int) -> None Constructs a graph with the given maximum number of vertices. """ super(Graph, self).__init__() self._numberOfVertices = 0 self._numberOfEdges = 0 self._vertex = Array(size) self._isDirected = False
def attachKey(self, obj): """ (NaryTree, Object) -> None Makes the given object the._key of this N-ary tree node. """ if not self.isEmpty: raise StateError self._key = obj self._subtree = Array(self._degree) for i in xrange(self._degree): self._subtree[i] = NaryTree(self._degree)
def depthFirstTraversal(self, visitor, start): """ (Graph, PrePostVisitor, Vertex) -> None Makes the given visitor visit the vertices of this graph in depth-first traversal order starting from the given vertex. """ assert isinstance(visitor, PrePostVisitor) visited = Array(self._numberOfVertices) for v in xrange(self._numberOfVertices): visited[v] = False self._depthFirstTraversal(visitor, self[start], visited)
def __init__(self, numberOfRows, numberOfColumns, numberOfElements): """ (SparseMatrixAsVector, int, int, int) -> None Constructs a sparse matrix with the given number of rows and columns and the given number of non-zero entries. """ super(SparseMatrixAsVector, self).__init__(numberOfRows, numberOfColumns) self._numberOfElements = numberOfElements self._array = Array(numberOfElements) for i in xrange(numberOfElements): self._array[i] = self.Entry()
def __init__(self, problem): """ (ScalesBalancingProblem.Node, ScalesBalancingProblem) -> None Constructs the initial node in the solution space of this scales balancing problem. """ self._problem = problem self._diff = 0 self._unplacedTotal = 0 self._numberPlaced = 0 self._pan = Array(self._problem._numberOfWeights) for i in range(self._problem._numberOfWeights): self._unplacedTotal += self._problem._weight[i]