Esempio n. 1
0
def writeTriples(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1, n):
            for k in range(j+1, n):
                if (a[i] + a[j] + a[k]) == 0:
                    stdio.writef('%d %d %d\n', a[i], a[j], a[k])
Esempio n. 2
0
def main1(argv):
    import stdio
    N = int(argv[1])
    samples = [ .2, .4, .5, .3, -.2, .4, .3, -.5, -.1, -.3 ]
    test = GuitarString(samples)
    for i in range(N):
        t = test.time()
        sample = test.sample()
        stdio.writef("%6d %8.4f\n", t, sample)
        test.tic()
Esempio n. 3
0
def main():
    """
    For testing:
    """
    import stdarray
    import stdio

    a = stdarray.readFloat1D()
    stdio.writef('       min %7.3f\n', min(a))
    stdio.writef('      mean %7.3f\n', mean(a))
    stdio.writef('       max %7.3f\n', max(a))
    stdio.writef('   std dev %7.3f\n', stddev(a))
    stdio.writef('    median %7.3f\n', median(a))
Esempio n. 4
0
 def writeReport(self):
     stdio.writeln(self._name)
     total = self._cash
     for i in range(self._stockCount):
         amount = self._shares[i]
         price = stockquote.priceOf(self._stocks[i])
         total += amount * price
         stdio.writef('%4d  %4s ', amount, self._stocks[i])
         stdio.writef('  %7.2f   %9.2f\n', price, amount * price)
     stdio.writef('%21s %10.2f\n', 'Cash:', self._cash)
     stdio.writef('%21s %10.2f\n', 'Total:', total)
Esempio n. 5
0
def main(argv):
    """
    For testing:
    """
    import stdio

    N = int(argv[1])
    t = [0.5, 0.3, 0.1, 0.1]
    for i in range(N):
        stdio.writef(" %2d ", uniformInt(-100, 100))
        stdio.writef("%8.5f ", uniformFloat(10.0, 99.0))
        if bernoulli(0.5):
            stdio.write("False ")
        else:
            stdio.write("True  ")
        stdio.writef("%7.5f ", gaussian(9.0, 0.2))
        stdio.writef("%2d ", discrete(t))
        stdio.writeln()
Esempio n. 6
0
def main():

    graphFile = sys.argv[1]
    delimiter = sys.argv[2]
    
    graph = Graph(graphFile, delimiter)
    
    vertexCount = graph.countV()
    edgeCount = graph.countE()
    stdio.writef('%d vertices, %d edges\n', vertexCount, edgeCount)
    
    avgDegree = averageDegree(graph)
    stdio.writef('average degree         = %7.3f\n', avgDegree)
    
    avgPathLength = averagePathLength(graph)
    stdio.writef('average path length    = %7.3f\n', avgPathLength)

    clusteringCoef = clusteringCoefficient(graph)
    stdio.writef('clustering coefficient = %7.3f\n', clusteringCoef)
Esempio n. 7
0
def main():

    graphFile = sys.argv[1]
    delimiter = sys.argv[2]
    
    graph = Graph(graphFile, delimiter)
    
    vertexCount = graph.countV()
    edgeCount = graph.countE()
    stdio.writef('%d vertices, %d edges\n', vertexCount, edgeCount)
    
    avgDegree = averageDegree(graph)
    stdio.writef('average degree         = %7.3f\n', avgDegree)
    
    avgPathLength = averagePathLength(graph)
    stdio.writef('average degree         = %7.3f\n', avgPathLength)

    clusteringCoef = clusteringCoefficient(graph)
    stdio.writef('clustering coefficient = %7.3f\n', clusteringCoef)
Esempio n. 8
0
def _main():
    """
    For testing:
    """
    import stdarray
    import stdio

    a = stdarray.readFloat1D()
    #stdio.writef('       min %7.3f\n', min(a))
    #stdio.writef('       max %7.3f\n', max(a))
    stdio.writef('      mean %7.3f\n', mean(a))
    stdio.writef('   std dev %7.3f\n', stddev(a))
    stdio.writef('    median %7.3f\n', median(a))
Esempio n. 9
0
def _main():
    x = float(sys.argv[1])
    y = float(sys.argv[2])
    rectangles = []
    while not stdio.isEmpty():
        lbound1 = stdio.readFloat()
        rbound1 = stdio.readFloat()
        lbound2 = stdio.readFloat()
        rbound2 = stdio.readFloat()
        rectangles += [Rectangle(Interval(lbound1, rbound1),
                                 Interval(lbound2, rbound2))]
    for i in range(len(rectangles)):
        stdio.writef('Area(%s) = %f\n', rectangles[i], rectangles[i].area())
        stdio.writef('Perimeter(%s) = %f\n', rectangles[i],
                     rectangles[i].perimeter())
        if rectangles[i].contains(x, y):
            stdio.writef('%s contains (%f, %f)\n', rectangles[i], x, y)
    for i in range(len(rectangles)):
        for j in range(i + 1, len(rectangles)):
            if rectangles[i].intersects(rectangles[j]):
                stdio.writef('%s intersects %s\n',
                             rectangles[i], rectangles[j])
Esempio n. 10
0
def main():

    n = int(sys.argv[1])

    stdio.writeln('Nanoseconds per operation')

    #-------------------------------------------------------------------
    # Empty loop
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(n):
            pass
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Empty loop')

    #-------------------------------------------------------------------
    # Integer addition
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = i + j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer addition')

    #-------------------------------------------------------------------
    # Integer subtraction
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = i - j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer subtraction')

    #-------------------------------------------------------------------
    # Integer multiplication
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = i * j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer multiplication')

    #-------------------------------------------------------------------
    # Integer division
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = i // j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer division')

    #-------------------------------------------------------------------
    # Integer remainder
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = i % j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer remainder')

    #-------------------------------------------------------------------
    # Comparison
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            b = (i < j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Comparison')

    #-------------------------------------------------------------------
    # Floating point addition
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = float(i) + float(j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Floating point addition')

    #-------------------------------------------------------------------
    # Floating point subtraction
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = float(i) - float(j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Floating point subtraction')

    #-------------------------------------------------------------------
    # Floating point multiplication
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = float(i) * float(j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Floating point multiplication')

    #-------------------------------------------------------------------
    # Floating point division
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = float(i) / float(j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Floating point division')

    #-------------------------------------------------------------------
    # Function call
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = f(i, j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Function call')

    #-------------------------------------------------------------------
    # math.sin
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n//10+1):
        for j in range(1, n+1):
            k = math.sin(i + j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n) * 10.0
    stdio.writef('%7.1f: %s\n', freq, 'math.sin')

    #-------------------------------------------------------------------
    # math.atan2
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n//10+1):
        for j in range(1, n+1):
            k = math.atan2(i, j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n) * 10.0
    stdio.writef('%7.1f: %s\n', freq, 'math.atan2')

    #-------------------------------------------------------------------
    # random.random
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n//10+1):
        for j in range(1, n+1):
            k = random.random()
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n) * 10.0
    stdio.writef('%7.1f: %s\n', freq, 'random.random')

    #-------------------------------------------------------------------
    # Integer addition
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n+1):
        for j in range(1, n+1):
            k = i + j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer addition again')
Esempio n. 11
0
# Compute M and N.
M = len(x)
N = len(y)

# Write edit distance between x and y.
stdio.write('Edit distance = ')
stdio.write(opt[0][0])
stdio.writeln()

# Recover and write an optimal alignment.
i = 0
j = 0

while i != M and j != N:
    if opt[i][j] == opt[i + 1][j] + 2:
        stdio.writef(x[i] + ' ' + '-' + ' ' + '2' + "\n")
        i += 1

    elif opt[i][j] == opt[i][j + 1] + 2:
        stdio.writef('-' + ' ' + y[j] + ' ' + '2' + "\n")
        j += 1

    elif (x[i]) == (y[j]):
        stdio.writef(x[i] + ' ' + y[j] + ' ' + '0' + "\n")
        i += 1
        j += 1

    else:
        stdio.writef(x[i] + ' ' + y[j] + ' ' + '1' + "\n")
        i += 1
        j += 1
    # Make one random move.
    r = random.random()
    sum = 0.0;
    for j in range(n):
        # Find interval containing r.
        sum += p[page][j]
        if r < sum:
            page = j
            break
    freq[page] += 1

    if i % 1000 == 0:
        # Plot histogram of frequencies
        stddraw.clear();
        for k in range(n):
            stddraw.line(k, 0, k, freq[k])
        stddraw.show()

# Print page ranks.
for i in range(n):
    stdio.writef("%8.5f", float(freq[i]) / float(t))
stdio.writeln()

stddraw.wait()

#-----------------------------------------------------------------------
# Example executions:
#
# python transition.py < tiny.txt | python randomsurferhistogram.py 1000000
# python transition.py < medium.txt | python randomsurferhistogram.py 1000000
Esempio n. 13
0
    # 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])
    now[page] = i

# Write the page ranks.
for v in hits:
    stdio.writef("%8.5f", 1.0 * v / moves)
stdio.writeln()

#print(hits)
#print(step)

for i in range(n):
    stdio.writef("%8.1f", 1.0 * step[i] / hits[i])
stdio.writeln()
#-----------------------------------------------------------------------

# python transition.py < tiny.txt | python randomsurfer.py 100
#  0.26000 0.27000 0.18000 0.26000 0.03000

# python transition.py < tiny.txt | python randomsurfer.py 10000
#  0.27410 0.26500 0.14570 0.24890 0.06630
Esempio n. 14
0
def main():
    y = float(sys.argv[1])
    x = invert(gaussian.cdf, y, -8.0, 8.0)
    stdio.writef('%.3f\n', x)
Esempio n. 15
0
for j in range(G + 1):
    opt[F][j] = 2 * (G - j)

# Initialize right column opt[i][G] (0 <= i <= F) to 2 * (F - i).
for i in range(F + 1):
    opt[i][G] = 2 * (F - i)

# Compute the rest of opt.
for j in reversed(range(G)):
    for i in reversed(range(F)):
        # of checks if there is a penalty or not
        if w[i] == z[j]:
            opt[i][j] = min(opt[i + 1][j + 1], opt[i + 1][j] + 2,
                            opt[i][j + 1] + 2)
        else:
            opt[i][j] = min(opt[i + 1][j + 1] + 1, opt[i + 1][j] + 2,
                            opt[i][j + 1] + 2)
# Write x, y, dimensions of opt, and opt.
stdio.writeln(w)
stdio.writeln(z)
stdio.write(F + 1)
stdio.write(' ')
stdio.writeln(G + 1)
for i in range(F + 1):
    for j in range(G + 1):
        if j != G:
            stdio.writef('%3d', opt[i][j])
            stdio.write(' ')
        else:
            stdio.writef('%3d\n', opt[i][j])
Esempio n. 16
0
x = stdio.readString()
y = stdio.readString()
stdio.readInt()
stdio.readInt()

# Compute M and N.
M = len(x)
N = len(y)
opt = stdarray.create2D(M + 1, N + 1, 0)
for i in range(M + 1):
    for j in range(N + 1):
        opt[i][j] = stdio.readInt()

# Write edit distance between x and y.
edit_distance = opt[0][0]
stdio.writef('Edit distance = %d\n', edit_distance)

# Recover and write an optimal alignment.
i = 0
j = 0
while i < M or j < N:
    if i == M or j == N:
        if i > j:
            stdio.writef('- %s 2\n', y[j])
        elif j > i:
            stdio.writef('%s - 2\n', x[i])
        break

    if opt[i][j] == opt[i + 1][j] + 2:
        stdio.writef('%s - 2\n', x[i])
        i += 1
Esempio n. 17
0
def attackLoop(enemy):

    stdio.writeln('What do you want to do?')
    stdio.writeln('\nattack / run\n')

    stdio.write(PROMPT)
    battleInput = stdio.readString()

    if battleInput == 'attack':
        if player['weapon'] == 'bone':
            atkDmg = random.randrange(weapon['bone base'],
                                      weapon['bone max'] + 1)
            enemy['Health'] -= atkDmg
            stdio.writef('\nYou strike the beast for %d damage.\n', atkDmg)

        else:
            atkDmg = random.randrange(weapon['none base'],
                                      weapon['none max'] + 1)
            enemy['Health'] -= atkDmg
            stdio.writef('\nYou strike the beast for %d damage.\n', atkDmg)

        if enemy['Health'] <= 0:
            stdio.writeln('The beast is dead. You catch your ' +
                          'breath and step over the body using ' +
                          'the walls as support. You slowly make ' +
                          'your way down the corridor until you\'re ' +
                          'blinded by sunlight. You\'ve escaped. ' +
                          'Good job!')
            stdio.writeln('\nPlay Again?\n')
            stdio.writeln('\nyes / no\n')
            stdio.write(PROMPT)
            tryAgain = stdio.readString()
            if tryAgain == 'yes':
                gameLoop()

            else:
                sys.exit()

    elif battleInput == 'run':
        escapeChance = random.randrange(1, 101)
        if escapeChance >= 80:
            stdio.writeln('\nYou make a dash down the hall ' +
                          'and don\'t stop running until you feel ' +
                          'the sunshine on your face. You\'ve done it.' +
                          ' You\'ve escaped. Good Job!')
            stdio.writeln('\nPlay Again?\n')
            stdio.writeln('\nyes / no\n')
            stdio.write(PROMPT)
            tryAgain = stdio.readString()

            if tryAgain == 'yes':
                main()

            elif tryAgain == 'no':
                sys.exit()

        else:
            stdio.writeln('\nYou try to escape but the ' + str(enemy['name']) +
                          ' catches you.')

    else:
        stdio.writeln('\nSorry, that\'s not a valid command')
        attackLoop(enemy)

    hurtDmg = random.randrange(enemy['attack low'], enemy['attack high'] + 1)
    player['Health'] -= hurtDmg
    stdio.writef('\nThe beast strikes you for %d damage.\n\n', hurtDmg)

    if player['Health'] <= 0:
        stdio.writeln('Alas, the beast has struck you down.' +
                      ' You\'ve failed to escape. Try again?')
        stdio.writeln('\nyes / no\n')
        stdio.write(PROMPT)

        tryAgain = stdio.readString()

        if tryAgain == 'yes':
            main()

        elif tryAgain == 'no':
            sys.exit()

    attackLoop(enemy)
Esempio n. 18
0
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()


#-----------------------------------------------------------------------

# Accept integer n as a command-line argument. Write to standard output
# a table of doubling ratios for the threesum problem of size n, n*2,
# n*4, etc.

n = int(sys.argv[1])
while True:
    previous = timeTrial(n // 2)
    current = timeTrial(n)
    ratio = current / previous
    stdio.writef('%7d %4.2f\n', n, ratio)
    n *= 2

#-----------------------------------------------------------------------

# python doublingtest.py 256
#     256 7.82
#     512 8.34
#    1024 7.96
#    2048 8.01
Esempio n. 19
0
def _main():
    """
    For testing.
    """
    import sys
    import stdio
    seed(1)
    n = int(sys.argv[1])
    for i in range(n):
        stdio.writef(' %2d '   , uniformInt(10, 100))
        stdio.writef('%8.5f '  , uniformFloat(10.0, 99.0))
        stdio.writef('%5s '    , bernoulli())
        stdio.writef('%5s '    , binomial(100, .5))
        stdio.writef('%7.5f '  , gaussian(9.0, .2))
        stdio.writef('%2d '    , discrete([.5, .3, .1, .1]))
        stdio.writeln()
Esempio n. 20
0
while not stdio.isEmpty():
    # Accumulate link counts.
    i = stdio.readInt()
    j = stdio.readInt()
    outDegrees[i] += 1
    linkCounts[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 * linkCounts[i][j] / outDegrees[i]) + (.10 / n)
        stdio.writef('%8.5f', p)
    stdio.writeln()

#-----------------------------------------------------------------------

# python transition.py < tiny.txt
# 5 5
#  0.02000 0.92000 0.02000 0.02000 0.02000
#  0.02000 0.02000 0.38000 0.38000 0.20000
#  0.02000 0.02000 0.02000 0.92000 0.02000
#  0.92000 0.02000 0.02000 0.02000 0.02000
#  0.47000 0.02000 0.47000 0.02000 0.02000
 
# python transition.py < medium.txt
# (Output omitted.)
Esempio n. 21
0
#       6        6.7
#       7        5.8
#       8        5.1
#       9        4.6

counts = stdarray.create1D(10, 0)  # frequency of leading digit i
n = 0  # number of items read in

while not stdio.isEmpty():
    x = stdio.readInt()  # read in next integer
    digit = leadingDigit(x)  # compute leading digit
    counts[digit] += 1  # update frequency
    n += 1

# Write the frequency distribution.
for i in range(1, len(counts)):
    stdio.writef("%d: %6.1f%%\n", i, 100.0 * float(counts[i]) / float(n))

#-----------------------------------------------------------------------

# python benford.py < princeton-files.txt
# 1:   30.8%
# 2:   19.3%
# 3:   13.0%
# 4:    9.9%
# 5:    7.4%
# 6:    5.9%
# 7:    5.2%
# 8:    4.4%
# 9:    4.1%
Esempio n. 22
0
import sys
import stdio
from charge import Charge

# Accept floats x and y as command-line arguments. Create two Charge
# objects with fixed position and electrical charge, and write to
# standard output the potential at (x, y) due to the two charges.

x = float(sys.argv[1])
y = float(sys.argv[2])
c1 = Charge(.51, .63, 21.3)
c2 = Charge(.13, .94, 81.9)
v1 = c1.potentialAt(x, y)
v2 = c2.potentialAt(x, y)
stdio.writef('potential at (%.2f, %.2f) due to\n', x, y)
stdio.writeln('  ' + str(c1) + ' and')
stdio.writeln('  ' + str(c2))
stdio.writef('is %.2e\n', v1+v2)

#-----------------------------------------------------------------------

# python chargeclient.py .2 .5
# potential at (0.20, 0.50) due to
#   21.3 at (0.51, 0.63) and
#   81.9 at (0.13, 0.94)
# is 2.22e+12

# python chargeclient.py .51 .94
# potential at (0.51, 0.94) due to
#   21.3 at (0.51, 0.63) and
Esempio n. 23
0
# 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()
    
#-----------------------------------------------------------------------

# more documents.txt 
# constitution.txt
# tomsawyer.txt
# huckfinn.txt
# prejudice.txt
def main():
    stockSymbol = sys.argv[1]
    price = priceOf(stockSymbol)
    stdio.writef('%.2f\n', price)
Esempio n. 25
0
delimiter = sys.argv[2]

graph = Graph()
instream = InStream(file)
while instream.hasNextLine():
    line = instream.readLine()
    names = line.split(delimiter)
    for i in range(1, len(names)):
        for j in range(i+1, len(names)):
            graph.addEdge(names[i], names[j])

degree  = smallworld.averageDegree(graph)
length  = smallworld.averagePathLength(graph)
cluster = smallworld.clusteringCoefficient(graph)

stdio.writef('number of vertices     = %d\n', graph.countV())
stdio.writef('average degree         = %7.3f\n', degree)
stdio.writef('average path length    = %7.3f\n', length)
stdio.writef('clustering coefficient = %7.3f\n', cluster)

#-----------------------------------------------------------------------

# cat tinymovies.txt
# Movie 1/Actor A/Actor B/Actor H
# Movie 2/Actor B/Actor C
# Movie 3/Actor A/Actor C/Actor G

# python performer.py tinymovies.txt "/"
# number of vertices     = 5
# average degree         =   2.800
# average path length    =   1.300
Esempio n. 26
0
def main():
    stockSymbol = sys.argv[1]
    price = priceOf(stockSymbol)
    stdio.writef('%.2f\n', price)
Esempio n. 27
0
def _main():
    """
    For testing.
    """
    import sys
    import stdio
    seed(1)
    n = int(input("Enter a number \n"))
    for i in range(n):
        stdio.writef(' %2d ', uniformInt(10, 100))
        stdio.writef('%8.5f ', uniformFloat(10.0, 99.0))
        stdio.writef('%5s ', bernoulli())
        stdio.writef('%5s ', binomial(100, .5))
        stdio.writef('%7.5f ', gaussian(9.0, .2))
        stdio.writef('%2d ', discrete([.5, .3, .1, .1]))
        stdio.writeln()
Esempio n. 28
0
#sine.py
#YULIU
#2019.7.30

import sys
import stdio
import math

times = 24
x = float(sys.argv[1]) * math.acos(-1)
sinx = 0
i = 1
while i <= times + 1:
    fac = j = 1
    t = 2 * i - 1
    #print(t)
    while j <= t:
        fac *= j
        j += 1
    #print(fac)
    an = (-1)**(i - 1) * (x**t) / fac
    sinx += an
    i += 1
format = '%.6f\n'
stdio.writef(format, sinx)
import gaussian

#-----------------------------------------------------------------------

# Accept a mean and standard deviation as command-line arguments.
# Write to standard output a table of the percentage of students
# scoring below certain scores on the SAT, assuming the test scores
# obey a Gaussian  distribution with the given mean and standard
# deviation.

mu = float(sys.argv[1])
sigma = float(sys.argv[2])

for score in range(400, 1600+1, 100):
    percent = gaussian.cdf(score, mu, sigma)
    stdio.writef('%4d  %.4f\n', score, percent)
 
#-----------------------------------------------------------------------

# python gaussiantable.py 1019 209
#  400  0.0015
#  500  0.0065
#  600  0.0225
#  700  0.0635
#  800  0.1474
#  900  0.2845
# 1000  0.4638
# 1100  0.6508
# 1200  0.8068
# 1300  0.9106
# 1400  0.9658
Esempio n. 30
0
def main(): 
    y = float(sys.argv[1])
    x = invert(gaussian.cdf, y, -8.0, 8.0)
    stdio.writef('%.3f\n', x)
def printMat(sol, m, n):
    for i in range(m):
        for j in range(n):
            stdio.writef('%3d ', sol[i][j])
        stdio.writeln()
Esempio n. 32
0
#YULIU
#2019.7.30

import sys
import stdio
import math

times = 24
x= float(sys.argv[1])*math.acos(-1)
cosx = 0
i = 0
while i <=times + 1:
    fac = 1
    j = 1
    t = 2*i
    #print(t)
    if t == 0:
        fac = 1
    else:
        while j <= t: 
            fac *= j
            j += 1
    #print(fac)
    an = (-1)**(i)*(x**t)/fac
    cosx += an
    i += 1
format = '%.6f\n'
stdio.writef(format,cosx)
    
    
Esempio n. 33
0
def _main():
    s = sys.argv[1]
    stdio.writef('zeros = %d, ones = %d, total = %d\n', zeros(s), ones(s),
                 len(s))
def main():
    lOfStockSymbol = sys.argv[1:]
    for stock in lOfStockSymbol:
        price = priceOf(stock)
        stdio.writef('%.2f\n', price)
Esempio n. 35
0
    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()

#-----------------------------------------------------------------------

# Accept integer n as a command-line argument. Write to standard output
# a table of doubling ratios for the threesum problem of size n, n*2,
# n*4, etc.

n = int(sys.argv[1])
while True:
    previous = timeTrial(n // 2)
    current  = timeTrial(n)
    ratio = current / previous
    stdio.writef('%7d %4.2f\n', n, ratio)
    n *= 2

#-----------------------------------------------------------------------

# python doublingtest.py 256
#     256 7.82
#     512 8.34
#    1024 7.96
#    2048 8.01
# ...

Esempio n. 36
0
# means.py: reads in positive real numbers from standard input and writes their
# geometric and harmonic means.

import math
import stdio

# Read floats from standard input into a list a.
a = stdio.readAllFloats()

# Define a variable n storing the length of a.
n = len(a)

# Define variables gm and hm to store the geometric and harmonic means of
# the numbers in a, with initial values 0.0.
gm, hm = 0.0, 0.0

# Iterate over the values in a and calculate their geometric and harmonic
# means. For geometric mean, consider taking logarithms to avoid overflow.
for value in a:
    gm += math.log(value)
gm = math.e**(gm / n)
for value in a:
    hm += 1 / value
hm = n / hm

# Write the results (geometric and harmonic means).
stdio.writef('geometric mean = %f, harmonic mean = %f\n', gm, hm)
Esempio n. 37
0
def main():

    n = int(sys.argv[1])

    stdio.writeln('Nanoseconds per operation')

    #-------------------------------------------------------------------
    # Empty loop
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(n):
            pass
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Empty loop')

    #-------------------------------------------------------------------
    # Integer addition
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = i + j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer addition')

    #-------------------------------------------------------------------
    # Integer subtraction
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = i - j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer subtraction')

    #-------------------------------------------------------------------
    # Integer multiplication
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = i * j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer multiplication')

    #-------------------------------------------------------------------
    # Integer division
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = i // j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer division')

    #-------------------------------------------------------------------
    # Integer remainder
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = i % j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer remainder')

    #-------------------------------------------------------------------
    # Comparison
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            b = (i < j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Comparison')

    #-------------------------------------------------------------------
    # Floating point addition
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = float(i) + float(j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Floating point addition')

    #-------------------------------------------------------------------
    # Floating point subtraction
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = float(i) - float(j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Floating point subtraction')

    #-------------------------------------------------------------------
    # Floating point multiplication
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = float(i) * float(j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Floating point multiplication')

    #-------------------------------------------------------------------
    # Floating point division
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = float(i) / float(j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Floating point division')

    #-------------------------------------------------------------------
    # Function call
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = f(i, j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Function call')

    #-------------------------------------------------------------------
    # math.sin
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n // 10 + 1):
        for j in range(1, n + 1):
            k = math.sin(i + j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n) * 10.0
    stdio.writef('%7.1f: %s\n', freq, 'math.sin')

    #-------------------------------------------------------------------
    # math.atan2
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n // 10 + 1):
        for j in range(1, n + 1):
            k = math.atan2(i, j)
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n) * 10.0
    stdio.writef('%7.1f: %s\n', freq, 'math.atan2')

    #-------------------------------------------------------------------
    # random.random
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n // 10 + 1):
        for j in range(1, n + 1):
            k = random.random()
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n) * 10.0
    stdio.writef('%7.1f: %s\n', freq, 'random.random')

    #-------------------------------------------------------------------
    # Integer addition
    #-------------------------------------------------------------------

    timer = stopwatch.Stopwatch()
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            k = i + j
    elapsed = timer.elapsedTime()
    freq = 1.0E9 * elapsed / float(n) / float(n)
    stdio.writef('%7.1f: %s\n', freq, 'Integer addition again')
Esempio n. 38
0
# 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)
        stdio.writef('%5.2f', p)
    stdio.writeln()

#-----------------------------------------------------------------------
# Example executions:
#
#    transition.py < tiny.txt
#    transition.py < medium.txt
Esempio n. 39
0
    # Make one random move.
    r = random.random()
    sum = 0.0
    for j in range(n):
        # Find interval containing r.
        sum += p[page][j]
        if r < sum:
            page = j
            break
    freq[page] += 1

    if i % 1000 == 0:
        # Plot histogram of frequencies
        stddraw.clear()
        for k in range(n):
            stddraw.line(k, 0, k, freq[k])
        stddraw.show()

# Print page ranks.
for i in range(n):
    stdio.writef("%8.5f", float(freq[i]) / float(t))
stdio.writeln()

stddraw.wait()

#-----------------------------------------------------------------------
# Example executions:
#
# python transition.py < tiny.txt | python randomsurferhistogram.py 1000000
# python transition.py < medium.txt | python randomsurferhistogram.py 1000000
    # 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

# Write the page ranks.
i = 0 
for v in hits:
    i += 1
    stdio.writef("%8.5f", 1.0 * v / moves)
    if i % 5 == 0:
        stdio.writeln()
stdio.writeln()

#-----------------------------------------------------------------------

# python transition.py < tiny.txt | python randomsurfer.py 100
#  0.26000 0.27000 0.18000 0.26000 0.03000

# python transition.py < tiny.txt | python randomsurfer.py 10000
#  0.27410 0.26500 0.14570 0.24890 0.06630

# python transition.py < tiny.txt | python randomsurfer.py 10000000
#  0.27308 0.26568 0.14616 0.24719 0.06789
 
Esempio n. 41
0
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()

# -----------------------------------------------------------------------

# python transition.py < tiny.txt | python3.4 markov.py 20
#  0.27245 0.26515 0.14669 0.24764 0.06806

# python transition.py < tiny.txt | python3.4 markov.py 40
#  0.27303 0.26573 0.14618 0.24723 0.06783
Esempio n. 42
0
    # 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):
        # Print probability for column j.
        p = (.90 * linkCounts[i][j] / outDegrees[i]) + (.10 / n)
        stdio.writef('%8.5f', p)
    stdio.writeln()

#-----------------------------------------------------------------------

# python transition.py < tiny.txt
# 5 5
#  0.02000 0.92000 0.02000 0.02000 0.02000
#  0.02000 0.02000 0.38000 0.38000 0.20000
#  0.02000 0.02000 0.02000 0.92000 0.02000
#  0.92000 0.02000 0.02000 0.02000 0.02000
#  0.47000 0.02000 0.47000 0.02000 0.02000

# python transition.py < medium.txt
# (Output omitted.)
Esempio n. 43
0
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()
Esempio n. 44
0
def main():
    s = sys.argv[1]
    stdio.writef('Zeros = %d, ones = %d, total = %d\n', Zeros(s), Ones(s),
                 len(s))
Esempio n. 45
0
# input and writes out the minimum and maximum values along with their ranks,
# ie, their positions (starting at 1) in the input.

import stdio

# Smallest and largest floats.
neg_inf = float('-inf')
pos_inf = float('inf')

# Read floats from standard input an into list a
a = stdio.readAllFloats()

# define variales to keep track of min and max values and rank.
min_val, min_rank = pos_inf, 0
max_val, max_rank = neg_inf, 0

# Iterate the list a to identify the minimum value and its rank and the
# maximum value and its rank. If v is smaller than min_val, update min_val
# to v and min_rank to i + 1; similarly, update max_val and max_rank.
for i, v in enumerate(a):
    if (v < min_val):
        min_val = v
        min_rank = i + 1
    if (v > max_val):
        max_val = v
        max_rank = i + 1

# Write the results (min_val, min_rank, max_val, max_rank).
stdio.writef('min val = %f, min rank = %d\n', min_val, min_rank)
stdio.writef('max val = %f, max rank = %d\n', max_val, max_rank)
Esempio n. 46
0
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:
    stdio.writef("%8.5f", 1.0 * v / moves)
stdio.writeln()

#-----------------------------------------------------------------------

# python transition.py < tiny.txt | python randomsurfer.py 100
#  0.26000 0.27000 0.18000 0.26000 0.03000

# python transition.py < tiny.txt | python randomsurfer.py 10000
#  0.27410 0.26500 0.14570 0.24890 0.06630

# python transition.py < tiny.txt | python randomsurfer.py 10000000
#  0.27308 0.26568 0.14616 0.24719 0.06789
 
Esempio n. 47
0
import sys
import stdio
from charge import Charge

x = float(sys.argv[1])
y = float(sys.argv[2])

c1 = Charge(.51, .63, 21.3)
c2 = Charge(.13, .84, 81.9)

v1 = c1.potentialAt(x, y)
v2 = c2.potentialAt(x, y)

stdio.writef('potential at (%.2f, %.2f) due to \n', x, y)
stdio.writeln(' ' + str(c1) + ' and')
stdio.writeln(' ' + str(c2))
stdio.writef('is %.2e\n', v1 + v2)
def _main():
    a = stdio.readAllStrings()
    reverse(a)
    for v in a[:-1]:
        stdio.writef('%s ', v)
    stdio.writeln(a[-1])
# standard input a sequence of coordinates (x_i, y_i, z_i), and writes the
# coordinates of the point closest to (x, y, z).

import stdio
import sys

# Read x, y, and z from command line, as floats.
x = float(sys.argv[1])
y = float(sys.argv[2])
z = float(sys.argv[3])

# Closest squared-distance so far, initialized to infinity.
bestD = float('inf')

# Read coordinates (xi, yi, zi) from standard input and calculate its
# squared-distance to the point (x, y, z). Check if that value is smaller
# than bestDist2, and if so, update bestDist2 to the new value, and
# let (bestx, besty, bestz) be (xi, yi, zi).
while stdio.isEmpty() is False:
    x1 = stdio.readFloat()
    y1 = stdio.readFloat()
    z1 = stdio.readFloat()
    if (((x - x1)**2 + (y - y1)**2 + (z - z1)**2) < bestD):
        cx = x1
        cy = y1
        cz = z1
        bestD = ((x - x1)**2 + (y - y1)**2 + (z - z1)**2)

# Write the closest point (bestx, besty, bestz).
stdio.writef('closest point = (%f, %f, %f)\n', cx, cy, cz)