def __init__(self, inStream): self._name = inStream.readLine() # Customer name self._cash = inStream.readFloat() # Cash balance self._stockCount = inStream.readInt() # Number of stocks # Stock symbols self._stocks = stdarray.create1D(self._stockCount, 0) # Share counts self._shares = stdarray.create1D(self._stockCount, 0) for i in range(self._stockCount): self._shares[i] = inStream.readInt() self._stocks[i] = inStream.readString()
def __init__(self, fileName): inStream = InStream(fileName) self._name = inStream.readLine() # Customer name self._cash = inStream.readFloat() # Cash balance self._stockCount = inStream.readInt() # Number of stocks # Stock symbols self._stocks = stdarray.create1D(self._stockCount, 0) # Share counts self._shares = stdarray.create1D(self._stockCount, 0) for i in range(self._stockCount): self._shares[i] = inStream.readInt() self._stocks[i] = inStream.readString()
def tone(hz, t): SPS = 44100 n = int(SPS * t) a = stdarray.create1D(n + 1, 0.0) for i in range(n + 1): a[i] = math.sin(2.0 * math.pi * i * hz / SPS) return a
def draw(pole): POLE_WIDTH = 0.01 POLE_COLOR = stddraw.RED DISC_COLOR = stddraw.BLUE n = len(pole) - 1 # Draw 3 poles. stddraw.clear() stddraw.setPenColor(POLE_COLOR) stddraw.setPenRadius(POLE_WIDTH) for i in range(3): stddraw.line(i, 0, i, n) # Draw n discs. discs = stdarray.create1D(3, 0) # discs[p] = # discs on pole p for i in range(n, 0, -1): stddraw.setPenColor(DISC_COLOR) stddraw.setPenRadius(0.035) # magic constant size = 0.5 * i / n p = pole[i] stddraw.line(p-size/2, discs[p], p + size/2, discs[p]) discs[p] += 1 stddraw.show(500.0)
def tone(hz, t): SPS = 44100 n = int(SPS * t) a = stdarray.create1D(n+1, 0.0) for i in range(n+1): a[i] = math.sin(2.0 * math.pi * i * hz / SPS) return a
def timeTrial(n): a = stdarray.create1D(n, 0) for i in range(n): a[i] = stdrandom.uniformInt(-1000000, 1000000) watch = Stopwatch() count = threesum.countTriples(a) return watch.elapsedTime()
def create(capacity): """ Create and return a ring buffer, with the given maximum capacity and with all elements initialized to None. A ring buffer is represented as a list of four elements: the buffer (buff) itself as a list; number of elements (size) currently in buff; the index (first) of the least recently inserted item; and the index (last) one beyond the most recently inserted item. """ # creating a four element as a list rb that is insialiazed. rb = stdarray.create1D(4, 0) # the first element create from capacity and return rb(ring buffer) rb[0] = stdarray.create1D(capacity) return rb
def __init__(self, text, k, d): freq = stdarray.create1D(d, 0) for i in range(len(text) - k + 1): kgram = text[i:i + k] h = hash(kgram) freq[h % d] += 1 vector = Vector(freq) self._sketch = vector.direction() # Unit vector
def trans(b=[]): c = stdarray.create1D(len(b)) for i in range(len(b)): if b[i] == '1': c[i] = True else: c[i] = False return c
def timeTrials(f, n, trials): total = 0.0 a = stdarray.create1D(n, 0.0) for t in range(trials): for i in range(n): a[i] = stdrandom.uniformFloat(0.0, 1.0) watch = Stopwatch() f(a) total += watch.elapsedTime() return total
def create(frequency): """ Create and return a guitar string of the given frequency, using a sampling rate given by SPS. A guitar string is represented as a ring buffer of of capacity N (SPS divided by frequency, rounded up to the nearest integer), with all values initialized to 0.0. """ n = math.ceiling(SPS / frequency) init = stdarray.create1D(n, 0.0) return create_from_samples(init)
def collect(n): found = stdarray.create1D(n, False) couponCount = 0 distinctCouponCount = 0 while distinctCouponCount < n: coupon = getCoupon(n) couponCount += 1 if not found[coupon]: distinctCouponCount += 1 found[coupon] = True return couponCount
def collect(n): found = stdarray.create1D(n + 1, False) couponCount = 0 distinctCouponCount = 0 while distinctCouponCount < n: coupon = getCouponbyBino(n) couponCount += 1 if not found[coupon] and coupon != 0: distinctCouponCount += 1 found[coupon] = True return couponCount
def create(capacity): """ Create and return a ring buffer, with the given maximum capacity and with all elements initialized to None. A ring buffer is represented as a list of four elements: the buffer (buff) itself as a list; number of elements (size) currently in buff; the index (first) of the least recently inserted item; and the index (last) one beyond the most recently inserted item. """ buffer = stdarray.create1D(capacity, None) rb = [buffer, 0, 0, 0] return rb
def multiplyMV(m, v): mRowCount = len(m) mColCount = len(m[0]) vLength = len(v) if mColCount != vLength: raise Exception('m col count must equal v length') prod = stdarray.create1D(mRowCount, 0.0) for i in range(mRowCount): for j in range(mColCount): prod[i] += m[i][j] * v[j] return prod
def __init__(self, filename): instream = InStream(filename) n = instream.readInt() radius = instream.readFloat() stddraw.setXscale(-radius, +radius) stddraw.setYscale(-radius, +radius) self._bodies = stdarray.create1D(n) self._xtracks = stdarray.create1D(n) self._ytracks = stdarray.create1D(n) for i in range(n): rx = instream.readFloat() ry = instream.readFloat() vx = instream.readFloat() vy = instream.readFloat() mass = instream.readFloat() r = Vector([rx, ry]) v = Vector([vx, vy]) self._bodies[i] = Body(r, v, mass) self._xtracks[i] = [] self._ytracks[i] = []
def multiplyVM(v, m): vLength = len(v) mRowCount = len(m) mColCount = len(m[0]) if vLength != mRowCount: raise Exception('v length must equal m row count') prod = stdarray.create1D(mColCount, 0.0) for j in range(mColCount): for i in range(mRowCount): prod[j] += m[i][j] * v[i] return prod
def __init__(self, filename): instream = InStream(filename) n = instream.readInt() radius = instream.readFloat() stddraw.setXscale(-radius, +radius) stddraw.setYscale(-radius, +radius) self._bodies = stdarray.create1D(n) for i in range(n): rx = instream.readFloat() ry = instream.readFloat() vx = instream.readFloat() vy = instream.readFloat() mass = instream.readFloat() r = Vector([rx, ry]) v = Vector([vx, vy]) self._bodies[i] = Body(r, v, mass)
def increaseTime(self, dt): # Initialize the forces to zero. n = len(self._bodies) f = stdarray.create1D(n, Vector([0, 0])) # Compute the forces. for i in range(n): for j in range(n): if i != j: bodyi = self._bodies[i] bodyj = self._bodies[j] f[i] = f[i] + bodyi.forceFrom(bodyj) # Move the bodies. for i in range(n): self._bodies[i].move(f[i], dt)
def main(): n = int(sys.argv[1]) p = float(sys.argv[2]) trials = int(sys.argv[3]) t = int(sys.argv[4]) q = evaluate(n, p, trials) stdio.writeln(q) norm = exTimes(n, p, trials, t) phi = stdarray.create1D(n + 1, 0.0) stddev = math.sqrt(n) / 2.0 for i in range(n + 1): phi[i] = gaussian.pdf(i, n / 2.0, stddev) stddraw.setCanvasSize(1000, 400) stddraw.setYscale(0, 1.1 * max(max(norm), max(phi))) stdstats.plotBars(norm) stdstats.plotLines(phi) stddraw.show()
def draw(pole): n = len(pole) - 1 # Draw 3 poles. stddraw.clear() stddraw.setPenColor(POLE_COLOR) stddraw.setPenRadius(POLE_WIDTH) for i in range(3): stddraw.line(i, 0, i, n) # Draw n discs. discs = stdarray.create1D(3, 0) # discs[p] = # discs on pole p for i in range(n, 0, -1): stddraw.setPenColor(DISC_COLOR) stddraw.setPenRadius(0.035) # magic constant size = 0.5 * i / n p = pole[i] stddraw.line(p-size/2, discs[p], p + size/2, discs[p]) discs[p] += 1 stddraw.sleep(500) stddraw.show()
def increaseTime(self, dt): # Initialize the forces to zero. n = len(self._bodies) f = stdarray.create1D(n, Vector([0, 0])) # Compute the forces. for i in range(n): for j in range(n): if i != j: bodyi = self._bodies[i] bodyj = self._bodies[j] f[i] = f[i] + bodyi.forceFrom(bodyj) # Move the bodies. for i in range(n): current_body = self._bodies[i] current_body.move(f[i], dt) self._xtracks[i].append(current_body._r[0]) self._ytracks[i].append(current_body._r[1]) # print(n) if n == 10: np.save("xtracks.npy", self._xtracks) np.save("ytracks.npy", self._ytracks)
import sys import random t = int(sys.argv[1]) # number of moves n = stdio.readInt() # number of pages stdio.readInt() # ignore integer required by input format # Read transition matrix. # p[i][j] = prob. that surfer moves from page i to page j p = stdarray.create2D(n, n, 0.0) for i in range(n): for j in range(n): p[i][j] = stdio.readFloat() # freq[i] = # times surfer hits page i freq = stdarray.create1D(n, 0) # Start at page 0. page = 0 stddraw.createWindow() stddraw.setXscale(-1, n) stddraw.setYscale(0, t) #stddraw.setPenRadius(.5/float(n)) stddraw.setPenRadius() for i in range(t): # Make one random move. r = random.random() sum = 0.0; for j in range(n): # Find interval containing r.
def __init__(self, n): self._freq = stdarray.create1D(n, 0.0) # Frequency counts. self._max = 0.0 # Maximum frequency.
import stdio import stdarray from charge import Charge from color import Color from picture import Picture # Read values from standard input to create an array of charged # particles. Set each pixel color in an image to a grayscale value # proportional to the total of the potentials due to the particles at # corresponding points. Draw the resulting image to standard draw. MAX_GRAY_SCALE = 255 # Read charges from standard input into an array. n = stdio.readInt() charges = stdarray.create1D(n) for i in range(n): x0 = stdio.readFloat() y0 = stdio.readFloat() q0 = stdio.readFloat() charges[i] = Charge(x0, y0, q0) # Create a Picture depicting potential values. pic = Picture() for col in range(pic.width()): for row in range(pic.height()): # Compute pixel color. x = 1.0 * col / pic.width() y = 1.0 * row / pic.height() v = 0.0
# transition.py #----------------------------------------------------------------------- import stdio import stdarray # Read links from standard input and write the corresponding # transition matrix to standard output. First, process the input # to count the outlinks from each page. Then apply the 90-10 rule to # compute the transition matrix. Assume that there are no pages that # have no outlinks in the input. n = stdio.readInt() counts = stdarray.create2D(n, n, 0) outDegree = stdarray.create1D(n, 0) while not stdio.isEmpty(): # Accumulate link counts. i = stdio.readInt() j = stdio.readInt() outDegree[i] += 1 counts[i][j] += 1 stdio.writeln(str(n) + ' ' + str(n)) for i in range(n): # Print probability distribution for row i. for j in range(n): # Print probability for column j. p = .90 * float(counts[i][j])/float(outDegree[i]) + .10/float(n)
import sys import stdrandom import stddraw import stdarray from turtle import Turtle # Accept as command-line arguments an integer turtleCount, an integer # stepCount, and a float stepSize. Create turtleCount Turtle objects, # and have them make stepCount random steps of size stepSize. turtleCount = int(sys.argv[1]) stepCount = int(sys.argv[2]) stepSize = float(sys.argv[3]) stddraw.setPenRadius(0.0) stddraw.clear(stddraw.LIGHT_GRAY) turtles = stdarray.create1D(turtleCount) for i in range(turtleCount): x = stdrandom.uniformFloat(0.0, 1.0) y = stdrandom.uniformFloat(0.0, 1.0) turtles[i] = Turtle(x, y, 0.0) for j in range(stepCount): for i in range(turtleCount): turtles[i].turnLeft(stdrandom.uniformFloat(0.0, 360.0)) turtles[i].goForward(stepSize) stddraw.show(0.0) stddraw.show() #----------------------------------------------------------------------- # python drunks.py 20 500 .005
#----------------------------------------------------------------------- import stdio import sys import stdarray import random # Accept integers m and n as command-line arguments. Write to standard # output a random sample of m integers in the range 0...n-1 (no # duplicates). m = int(sys.argv[1]) # choose this many elements n = int(sys.argv[2]) # from 0, 1, ..., n-1 # Initialize perm. perm = stdarray.create1D(n, 0) for i in range(n): perm[i] = i # Create random sample in perm[0], perm[1], ..., perm[m-1] for i in range(m): # Choose a random integer r between i and n-1. r = random.randrange(i, n) # Swap perm[i] and perm[r]. temp = perm[r] perm[r] = perm[i] perm[i] = temp # Write the results.
from charge import Charge import stddraw import stdarray from picture import Picture from color import Color a = stdarray.create1D(3) a[0] = Charge(.4, .6, 50) a[1] = Charge(.5, .5, -5) a[2] = Charge(.6, .6, 50) MAX_GRAY_SCALE = 255 p = Picture() stddraw.setCanvasSize(p.width(),p.height()) for t in range(100): # Compute the picture p. for col in range(p.width()): for row in range(p.height()): # Compute pixel color. x = 1.0 * col / p.width() y = 1.0 * row / p.height() v = 0.0 for i in range(3): v += a[i].potentialAt(x, y) v = (MAX_GRAY_SCALE / 2.0) + (v / 2.0e10) if v < 0: grayScale = 0 elif v > MAX_GRAY_SCALE: grayScale = MAX_GRAY_SCALE else:
#----------------------------------------------------------------------- # Accept string fileName and integer fieldCount as command-line # arguments. Split the file whose name is fileName.csv, by field, # into fieldCount+1 files named fileName1.txt, fileName2.txt, etc. DELIM = ',' fileName = sys.argv[1] fieldCount = int(sys.argv[2]) # Create the input stream. inStream = InStream(fileName + '.csv') # Create output streams. outStreams = stdarray.create1D(fieldCount) for i in range(fieldCount): file = OutStream(fileName + str(i) + '.txt') outStreams[i] = file # Read lines from the input stream and write them to the # output stream. while inStream.hasNextLine(): line = inStream.readLine() fields = line.split(DELIM) for i in range(fieldCount): outStreams[i].writeln(fields[i]) #----------------------------------------------------------------------- # more djia.csv
def hanoi(n): # pole[i] = pole (0-2) that disc i is on. pole = stdarray.create1D(n+1, 0) draw(pole) hanoiHelp(n, 0, 1, 2, pole)
moves = int(sys.argv[1]) n = stdio.readInt() stdio.readInt() # Discard the second int of standard input. # Read the transition matrix from standard input. # probs[i][j] is the probability that the surfer moves from # page i to page j. probs = stdarray.create2D(n, n, 0.0) for i in range(n): for j in range(n): probs[i][j] = stdio.readFloat() # Use the power method to compute page ranks. ranks = stdarray.create1D(n, 0.0) ranks[0] = 1.0 for i in range(moves): # Compute effect of next move on page ranks. newRanks = stdarray.create1D(n, 0.0) for j in range(n): # New rank of page j is dot product # of old ranks and column j of probs. for k in range(n): newRanks[j] += ranks[k] * probs[k][j] ranks = newRanks # Write the page ranks. for rank in ranks: stdio.writef("%8.5f", rank) stdio.writeln()
def sort(a): n = len(a) aux = stdarray.create1D(n) _sort(a, 0, n, aux)
def __init__(self, n): # Frequency counts. self._freqCounts = stdarray.create1D(n, 0)
import stdaudio # Read sound samples from standard input, and play the sound to # standard audio. SPS = 44100 CONCERT_A = 440.0 NOTES_ON_SCALE = 12.0 while not stdio.isEmpty(): pitch = stdio.readInt() duration = stdio.readFloat() hz = CONCERT_A * (2.0 ** (pitch / NOTES_ON_SCALE)) n = int(SPS * duration) note = stdarray.create1D(n+1, 0.0) for i in range(n+1): note[i] = math.sin(2.0 * math.pi * i * hz / SPS) stdaudio.playSamples(note) stdaudio.wait() #----------------------------------------------------------------------- # python playthattune.py < elise.txt # python playthattune.py < ascale.txt # python playthattune.py < entertainer.txt # python playthattune.py < firstcut.txt
return result #----------------------------------------------------------------------- # Accept integer command-line argument n, compute n terms # of the Taylor series e^x = 1 + x + x^2/2! + .... Then read # values x from standard input, and write to standard output the # polynomial evaluated at x. Also write to standard output the # value computed by math.exp(x). n = int(sys.argv[1]) # Compute coeffients for Taylor series # e^x = 1 + x + x^2/2! + x^3/3! + ... a = stdarray.create1D(n, 0.0) a[0] = 1.0 for i in range(1, n): a[i] = a[i - 1] / float(i) # Evaluate the polynomial at values x read from standard input. while not stdio.isEmpty(): x = stdio.readFloat() stdio.writeln(evaluate(x, a)) stdio.writeln(math.exp(x)) stdio.writeln() #----------------------------------------------------------------------- # python horner.py 30 # 0
import sys from charge import Charge from color import Color from picture import Picture # Read values from standard input to create an array of charged # particles. Set each pixel color in an image to a grayscale value # proportional to the total of the potentials due to the particles at # corresponding points. Draw the resulting image to standard draw. MAX_GRAY_SCALE = 255 # Read charges from standard input into an array. #n = stdio.readInt() n = eval(sys.argv[1]) charges = stdarray.create1D(n) for i in range(n): x0 = round(stdrandom.uniformFloat(0, 1), 2) y0 = round(stdrandom.uniformFloat(0, 1), 2) q0 = stdrandom.gaussian(50, 150) charges[i] = Charge(x0, y0, q0) print(str(charges[i])) # Create a Picture depicting potential values. pic = Picture() for col in range(pic.width()): for row in range(pic.height()): # Compute pixel color. x = 1.0 * col / pic.width() y = 1.0 * row / pic.height() v = 0.0
import stdarray import stddraw import sys import math # Accept integer command-line argument n. Plot the function # y = sin(4x) + sin(20x) # between x = 0 and x = pi by drawing n line segments. # Accept the number of line segments to plot. n = int(sys.argv[1]) stddraw.createWindow() # The function y = sin(4x) + sin(20x), sampled at n points # between x = 0 and x = pi. x = stdarray.create1D(n+1, 0.0) y = stdarray.create1D(n+1, 0.0) for i in range(n+1): x[i] = math.pi * i / n y[i] = math.sin(4.0*x[i]) + math.sin(20.0*x[i]) # Rescale the coordinate system. stddraw.setXscale(0, math.pi) stddraw.setYscale(-2.0, +2.0) # Plot the approximation to the function. for i in range(n): stddraw.line(x[i], y[i], x[i+1], y[i+1]) stddraw.show() stddraw.wait()
import sys import stdarray from matrix import multiplyVM moves = int(sys.argv[1]) p = stdarray.readFloat2D() ranks = stdarray.create1D(len(p), 0.0) ranks[0] = 1.0 for i in range(moves): ranks = multiplyVM(ranks, p) stdarray.write1D(ranks)
import stdstats import gaussian #----------------------------------------------------------------------- # Accept integers n and trials as command-line arguments. # Perform trials experiments, each of which counts the number # of heads found when a fair coin is flipped n times. Then # draw the results to standard draw. Also draw the predicted Gaussian # distribution function, thereby allowing easy comparison of the # experimental results to the theoretically predicted results. n = int(sys.argv[1]) trials = int(sys.argv[2]) freq = stdarray.create1D(n+1, 0) for t in range(trials): heads = stdrandom.binomial(n, 0.5) freq[heads] += 1 norm = stdarray.create1D(n+1, 0.0) for i in range(n+1): norm[i] = 1.0 * freq[i] / trials phi = stdarray.create1D(n+1, 0.0) stddev = math.sqrt(n)/2.0 for i in range(n+1): phi[i] = gaussian.pdf(i, n/2.0, stddev) stddraw.setCanvasSize(1000, 400) stddraw.setYscale(0, 1.1 * max(max(norm), max(phi)))
import stdaudio, sys, random, math, stdstats, stddraw, stdarray brown_v = stdarray.create1D(882000, 0.0) white = [random.uniform(-0.25, 0.25) for i in range(882000)] variance = 0.05 i = 0 i1 = 882000 f = 0.25 def fill_brownian(brown_v, i, i1, variance, scale): #base condtion; when the differences between indexes = 1 # i.e. theyre next to each other if i1 - i == 1: return else: #find middle index mid_index = (i + i1) // 2 #calculate midpoint value avg = (brown_v[i] + brown_v[i1]) / 2 #add random number from normal distribution to midpoint value delta = random.gauss(0, math.sqrt(variance)) mp = avg + delta #set new variance new_var = variance / scale #add to array brown_v[mid_index] = mp #call brownian before midpoint(inclusive) fill_brownian(brown_v, i, mid_index, new_var, scale)
from instream import InStream from sketch import Sketch #----------------------------------------------------------------------- # Accept integers k and d as command-line arguments. Read a document # list from standard input, compute profiles based on k-gram # frequencies for all the documents, and write a matrix of similarity # measures between all pairs of documents. d is the dimension of the # profiles. k = int(sys.argv[1]) d = int(sys.argv[2]) filenames = stdio.readAllStrings() sketches = stdarray.create1D(len(filenames)) for i in range(len(filenames)): text = InStream(filenames[i]).readAll() sketches[i] = Sketch(text, k, d) stdio.write(' ') for i in range(len(filenames)): stdio.writef('%8.4s', filenames[i]) stdio.writeln() for i in range(len(filenames)): stdio.writef('%.4s', filenames[i]) for j in range(len(filenames)): stdio.writef('%8.2f', sketches[i].similarTo(sketches[j])) stdio.writeln()
def superpose(a, b, aWeight, bWeight): c = stdarray.create1D(len(a), 0.0) for i in range(len(a)): c[i] = a[i]*aWeight + b[i]*bWeight return c
#----------------------------------------------------------------------- import stdio import sys import stdarray import random # Accept integer n as a command-line argument. Write to standard # output the number of coupons you collect before obtaining one of # each of n types. n = int(sys.argv[1]) count = 0 collectedCount = 0 isCollected = stdarray.create1D(n, False) while collectedCount < n: # Generate another coupon. value = random.randrange(0, n) count += 1 if not isCollected[value]: collectedCount += 1 isCollected[value] = True stdio.writeln(count) #----------------------------------------------------------------------- # python couponcollector.py 1000 # 8507
# transition.py #----------------------------------------------------------------------- import stdio import stdarray # Read links from standard input and write the corresponding # transition matrix to standard output. First, process the input # to count the outlinks from each page. Then apply the 90-10 rule to # compute the transition matrix. Assume that there are no pages that # have no outlinks in the input. n = stdio.readInt() linkCounts = stdarray.create2D(n, n, 0) outDegrees = stdarray.create1D(n, 0) while not stdio.isEmpty(): # Accumulate link counts. i = stdio.readInt() j = stdio.readInt() if not linkCounts[i][j]: outDegrees[i] += 1 linkCounts[i][j] += 1 print(linkCounts) stdio.writeln(str(n) + ' ' + str(n)) for i in range(n): # Print probability distribution for row i. for j in range(n):
def __sub__(self, other): result = stdarray.create1D(self._n, 0) for i in range(self._n): result[i] = self._coords[i] - other._coords[i] return Vector(result)
moves = int(sys.argv[1]) n = stdio.readInt() stdio.readInt() # Discard the second int of standard input. # Read the transition matrix from standard input. # p[i][j] is the probability that the surfer moves from # page i to page j. p = stdarray.create2D(n, n, 0.0) for i in range(n): for j in range(n): p[i][j] = stdio.readFloat() # Perform the simulation, thus computing the hits array. # hits[i] is the number of times the surfer hits page i. hits = stdarray.create1D(n, 0) page = 0 # Start at page 0. for i in range(moves): # Make one random move. r = random.random() sum = 0.0 for j in range(0, n): # Find interval containing r. sum += p[page][j] if r < sum: page = j break hits[page] += 1 # Write the page ranks. for v in hits:
def scale(self, alpha): result = stdarray.create1D(self._n, 0) for i in range(self._n): result[i] = alpha * self._coords[i] return Vector(result)
# ----------------------------------------------------------------------- import stdio import sys import stdarray import random # Accept integers m and n as command-line arguments. Write to standard # output a random sample of m integers in the range 0...n-1 (no # duplicates). m = int(sys.argv[1]) # choose this many elements n = int(sys.argv[2]) # from 0, 1, ..., n-1 # Initialize perm. perm = stdarray.create1D(n, 0) for i in range(n): perm[i] = i # Create random sample in perm[0], perm[1], ..., perm[m-1] for i in range(m): # Choose a random integer r between i and n-1. r = random.randrange(i, n) # Swap perm[i] and perm[r]. temp = perm[r] perm[r] = perm[i] perm[i] = temp # Write the results. for i in range(m):
moves = int(sys.argv[1]) n = stdio.readInt() stdio.readInt() # Discard the second int of standard input. # Read the transition matrix from standard input. # p[i][j] is the probability that the surfer moves from # page i to page j. p = stdarray.create2D(n, n, 0.0) for i in range(n): for j in range(n): p[i][j] = stdio.readFloat() # Perform the simulation, thus computing the hits array. # hits[i] is the number of times the surfer hits page i. hits = stdarray.create1D(n, 0) step = stdarray.create1D(n, 0) now = stdarray.create1D(n, 0) page = 0 # Start at page 0. for i in range(moves): # Make one random move. r = random.random() total = 0.0 for j in range(0, n): # Find interval containing r. total += p[page][j] if r < total: page = j break hits[page] += 1 step[page] += (i - now[page])
import stdio import stdarray import sys import random # Accept integer n as a command-line argument. Simulate how long it # takes n random walkers starting at the center of an n-by-n grid to # visit every cell in the grid. Write the number of steps to standard # output. n = int(sys.argv[1]) # Create arrays indicating the x and y positions of the walkers. # All walkers begin at the middle of the grid. x = stdarray.create1D(n, n // 2) # x positions y = stdarray.create1D(n, n // 2) # y positions cellsToVisit = n * n # Create visited, an array that keeps track of which cells have # been visited so far. visited = stdarray.create2D(n, n, False) # has (i,j) been visited? visited[n // 2][n // 2] = True cellsToVisit -= 1 # Run the simulation. steps = 0 while cellsToVisit > 0: steps += 1 for i in range(n):
#----------------------------------------------------------------------- # primesieve.py #----------------------------------------------------------------------- import stdio import stdarray import sys # Accept integer n as a command-line argument. Write to standard # output the number of primes <= n. n = int(sys.argv[1]) # Initially assume all integers are prime. isPrime = stdarray.create1D(n+1, True) # Mark non-primes <= n using the Sieve of Eratosthenes. for i in range(2, n): if (isPrime[i]): # Mark multiples of i as nonprime. for j in range(2, n//i + 1): isPrime[i * j] = False; #i = 2 #while i <= n//i: # if isPrime[i]: # # Mark multiples of i as nonprime. # j = i # while j <= n//i: # isPrime[i * j] = False # j += 1