def _main(): """ For testing. """ import os import math from algs4.stdlib import stdio, instream _createTextAudioFile() stdio.writeln('Creating and playing in small chunks...') sps = _SAMPLES_PER_SECOND inStream = instream.InStream('looney.txt') while not inStream.isEmpty(): pitch = inStream.readInt() duration = inStream.readFloat() hz = 440 * math.pow(2, pitch / 12.0) N = int(sps * duration) notes = [] for i in range(N + 1): notes.append(math.sin(2 * math.pi * i * hz / sps)) playSamples(notes) wait() stdio.writeln('Creating and playing in one large chunk...') sps = _SAMPLES_PER_SECOND notes = [] inStream = instream.InStream('looney.txt') while not inStream.isEmpty(): pitch = inStream.readInt() duration = inStream.readFloat() hz = 440 * math.pow(2, pitch / 12.0) N = int(sps * duration) for i in range(N + 1): notes.append(math.sin(2 * math.pi * i * hz / sps)) playSamples(notes) wait() stdio.writeln('Saving...') save('looney', notes) stdio.writeln('Reading...') notes = read('looney') stdio.writeln('Playing an array...') playSamples(notes) wait() stdio.writeln('Playing a file...') playFile('looney') wait() os.remove('looney.wav') os.remove('looney.txt')
For additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. """ import sys from algs4.stdlib import instream from algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph from algs4.graphs.directed_edge import DirectedEdge from algs4.graphs.acyclic_lp import AcyclicLp # Try this with the jobsPC.txt data file if __name__ == '__main__': # Create stream from file or the standard input, # depending on whether a file name was passed. file = sys.argv[1] if len(sys.argv) > 1 else None stream = instream.InStream(file) # Number of jobs N = stream.readInt() # Source and sink source, sink = 2 * N, 2 * N + 1 # Construct the network G = EdgeWeightedDigraph(2 * N + 2) for i in range(N): duration = stream.readFloat() G.add_edge(DirectedEdge(i, i + N, duration)) G.add_edge(DirectedEdge(source, i, 0.0)) G.add_edge(DirectedEdge(i + N, sink, 0.0))
def has_cycle(self): """ Does the edge weighted digraph have a directed cycle? :returns: true if there is a cycle, false otherwise """ return self._cycle != None def cycle(self): """ Returns a directed cycle if the edge weighted digraph has a directed cycle, and null otherwise. :returns: a directed cycle (as an iterable) if the digraph has a directed cycle, and null otherwise """ return self._cycle import sys from algs4.stdlib import instream from algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph if __name__ == '__main__': # Create stream from file or the standard input, # depending on whether a file name was passed. stream = sys.argv[1] if len(sys.argv) > 1 else None d = EdgeWeightedDigraph.from_stream(instream.InStream(stream)) cyc = EdgeWeightedDirectedCycle(d) print(cyc.cycle())