예제 #1
0
def main(argv):

    fileName = argv[1]
    w = int(argv[2])
    h = int(argv[3])

    source = picture.Picture()
    source.load(fileName)

    target = picture.Picture(w, h)

    for ti in range(w):
        for tj in range(h):
            si = ti * source.width() // w
            sj = tj * source.height() // h
            target.set(ti, tj, source.get(si, sj))

    maxHeight = max(source.height(), target.height())

    stddraw.createWindow(source.width() + target.width(), maxHeight)
    stddraw.setXscale(0, source.width() + target.width())
    stddraw.setYscale(0, maxHeight)

    stddraw.picture(source, source.width() / 2, maxHeight / 2)
    stddraw.picture(target, source.width() + target.width() / 2, maxHeight / 2)

    stddraw.show()
    stddraw.wait()
예제 #2
0
def md(mu=1019,sigma=209):
	phi = []
	for i in range(400,1600,50):
		phi.append(gaussian.pdf(i,mu,sigma))
	stddraw.setYscale(0,1.1*max(phi))
	stdstats.plotLines(phi)
	stddraw.show()
예제 #3
0
def draw(a, which):
    n = len(a[0])
    stddraw.setXscale(-.5 * n, n + .5)
    stddraw.setYscale(-.5 * n, n + .5)
    for i in range(n):
        for j in range(n):
            if a[i][j] == which:
                if i % 2 == 0:
                    stddraw.line(j - .5 * i / 2,
                                 n - i / 2 * (1 * math.sin(math.pi / 3)) - 1,
                                 j - .5 * i / 2 + .98,
                                 n - i / 2 * (1 * math.sin(math.pi / 3)) - 1)
                else:
                    if j % 2 == 0:
                        jt = j / 2 - (i - 1) / 2 * .5
                        stddraw.line(
                            jt,
                            n - (i - 1) / 2 * (1 * math.sin(math.pi / 3)) - 1,
                            jt - .5,
                            n - (i + 1) / 2 * (1 * math.sin(math.pi / 3)) - 1)
                    else:
                        jt = (j + 1) / 2 - (i - 1) / 2 * .5
                        stddraw.line(
                            jt - 1,
                            n - (i - 1) / 2 * (1 * math.sin(math.pi / 3)) - 1,
                            jt + .5 - 1,
                            n - (i + 1) / 2 * (1 * math.sin(math.pi / 3)) - 1)
예제 #4
0
def main(argv):
    M = int(argv[1])
    N = int(argv[2])
    S = int(argv[3])

    # Create a RandomQueue object containing Queue objects.
    servers = randomqueue.RandomQueue()
    for i in range(M):
        servers.enqueue(linkedlistqueue.Queue())

    for j in range(N):
        # Assign an item to a server.
        min = servers.sample()
        for k in range(1, S):
            # Pick a random server, update if new min.
            q = servers.sample()
            if len(q) < len(min):
                min = q
        # min is the shortest server queue.
        min.enqueue(j)

    lengths = []
    for q in servers:
        lengths += [len(q)]
    stddraw.createWindow()
    stddraw.setYscale(0, 2.0*N/M)
    stdstats.plotBars(lengths)
    stddraw.show()
    stddraw.wait()
예제 #5
0
def _main():
    earth = Body(vector.Vector([5, 5]), vector.Vector([0, 1]), 12)
    print(earth._r[0])
    stddraw.setXscale(0, 10)
    stddraw.setYscale(0, 10)
    earth.draw()
    stddraw.show()
예제 #6
0
def main(argv):
    M = int(argv[1])
    N = int(argv[2])
    S = int(argv[3])

    # Create a RandomQueue object containing Queue objects.
    servers = randomqueue.RandomQueue()
    for i in range(M):
        servers.enqueue(linkedlistqueue.Queue())

    for j in range(N):
        # Assign an item to a server.
        min = servers.sample()
        for k in range(1, S):
            # Pick a random server, update if new min.
            q = servers.sample()
            if len(q) < len(min):
                min = q
        # min is the shortest server queue.
        min.enqueue(j)

    lengths = []
    for q in servers:
        lengths += [len(q)]
    stddraw.createWindow()
    stddraw.setYscale(0, 2.0 * N / M)
    stdstats.plotBars(lengths)
    stddraw.show()
    stddraw.wait()
예제 #7
0
def main():
	#print(deck())
	a = deck()
	#b = popdeck(a,5)
	b = [16,2,4,1,0]
	r = pair(b)	#获得对数或三条数
	num = numofGroupDeck(b)	#获得牌面数字
	c = colorofGroupDeck(b)	#获得花色
	print('牌:',b)
	print('牌面数字:',num)
	print('花色:',c)
	print('一对:',onePair(r))
	print('两对:',twoPair(r))
	print('三条:',threeofAkind(r))
	print('满堂红:',fullHouse(r))
	print('同花:',flushColor(c))
	print('顺子:',straight(num))
	print('同花顺:',straightFlush(c,num))
	#统计各种情况出现概率
	n = 100000	#试验次数
	p = [0]*7	#记录各种情况结果
	for i in range(n):
		a = deck()
		b = popdeck(a,5)
		r = pair(b)
		num = numofGroupDeck(b)
		c = colorofGroupDeck(b)
		if onePair(r):
			p[0] += 1
		elif twoPair(r):
			p[1] += 1
		elif threeofAkind(r):
			p[2] += 1
		elif fullHouse(r):
			p[3] += 1
		if straightFlush(c,num):
			p[6] += 1
		elif flushColor(c):
			p[4] += 1
		elif straight(num):
			p[5] += 1
	print('p:',p)
	stddraw.setYscale(0,1.1*max(p))
	stdstats.plotBars(p)
	
	#使用数学公式验证,先选牌面数字,再选花色
	q = [0]*7
	q[0] = comb(13,1)*comb(4,2)*comb(12,3)*comb(4,1)**3/(comb(52,5))
	q[1] = comb(13,2)*comb(4,2)**2*comb(11,1)*comb(4,1)/(comb(52,5))
	q[2] = comb(13,1)*comb(4,3)*comb(12,2)*comb(4,1)**2/(comb(52,5))
	q[3] = comb(13,1)*comb(4,3)*comb(12,1)*comb(4,2)/(comb(52,5))
	flush = comb(13,5)*comb(4,1)/(comb(52,5))
	Straight = 9*comb(4,1)**5/(comb(52,5))
	q[6] = flush*Straight
	q[4] = flush-q[6]
	q[5] = Straight-q[6]
	for i in range(len(q)):
		print('q[i]:{:.4f}'.format(q[i]))

	stddraw.show()
    def __init__(self,
                 goalie_pos_start,
                 GRID_NUM_HEIGHT=8,
                 GRID_NUM_WIDTH=5,
                 GRID_SIZE=75,
                 draw_scene=True,
                 gridworld=False):
        self.goalie_pos = goalie_pos_start
        self.GRID_NUM_HEIGHT = GRID_NUM_HEIGHT
        self.GRID_NUM_WIDTH = GRID_NUM_WIDTH
        self.GRID_SIZE = GRID_SIZE
        self.WIDTH = self.GRID_SIZE * self.GRID_NUM_WIDTH
        self.HEIGHT = self.GRID_SIZE * self.GRID_NUM_HEIGHT
        self.num_interations = 0
        self.draw_scene = draw_scene
        self.gridworld = gridworld

        self.ball_radius = GRID_SIZE / 2

        self.reset()

        if self.draw_scene:
            stddraw.setXscale(0, self.WIDTH)
            stddraw.setYscale(0, self.HEIGHT)
            stddraw.setCanvasSize(self.WIDTH, self.HEIGHT)
        time.sleep(1)
예제 #9
0
def draw(a, which):
    n = len(a)
    stddraw.setXscale(-.5, n)
    stddraw.setYscale(-.5, n)
    for i in range(n):
        for j in range(n):
            if a[i][j] == which:
                stddraw.filledSquare(j, n-i-1, .5)
예제 #10
0
def main():
    d = Data(10)
    for i in range(10):
        d.addDataPoint(i, i)
    stddraw.setYscale(d.minData(), 1.1 * d.maxData())
    d.plotTukey()
    d.plot()
    stddraw.show()
예제 #11
0
def drawRuler(n):
    s = ruler(n)
    l = len(s)
    stddraw.setXscale(-1, l + 1)
    stddraw.setYscale(0, n * 1.1)
    for i in range(l):
        stddraw.line(i, 0, i, eval(s[i]))
    stddraw.show()
예제 #12
0
def draw(a, which):
    n = len(a)
    stddraw.setXscale(-.5, n)
    stddraw.setYscale(-.5, n)
    for i in range(n):
        for j in range(n):
            if a[i][j] == which:
                stddraw.filledSquare(j, n - i - 1, .49)
예제 #13
0
def main():
    var = float(sys.argv[1])
    n = int(sys.argv[2])
    stddraw.setXscale(-1, +1)
    stddraw.setYscale(-1, +1)
    stddraw.setPenRadius(0.0)
    midpoint(0, 0, 0, 0, var / math.sqrt(2), n)
    stddraw.show()
예제 #14
0
def hanoi(n):
    DT = 1000
    t = 1.4
    l = []
    tow = []
    for i in range(3):
        tow.append([])
        for j in range(n):
            tow[i].append(0)
    for i in range(n):
        l.append(t**i)
    stddraw.setXscale(-1, t**n * 4)
    stddraw.setYscale(-1, n + 2)
    stddraw.line(t**n * 0.5, -1, t**n * 0.5, n + 1)
    stddraw.line(t**n * 1.5, -1, t**n * 1.5, n + 1)
    stddraw.line(t**n * 2.5, -1, t**n * 2.5, n + 1)
    tow[0] = l
    for i in range(n):
        stddraw.line(t**n * 0.5 - tow[0][i] / 2, n - i,
                     t**n * 0.5 + tow[0][i] / 2, n - i)
    stddraw.show(DT)

    global r
    for a in range(len(r)):
        stddraw.clear()

        stddraw.line(t**n / 2, -1, t**n / 2, n + 1)
        stddraw.line(t**n * 1.5, -1, t**n * 1.5, n + 1)
        stddraw.line(t**n * 2.5, -1, t**n * 2.5, n + 1)
        p = r[a][0]
        d = r[a][1]
        for i in range(3):
            flag = 0
            for j in range(n):
                #if j+1 == p:
                if tow[i][j] == t**(p - 1):
                    flag = 1
                    if d == 'l':
                        num = (i - 1) % 3
                    else:
                        num = (i + 1) % 3
                    temp = tow[i][j]
                    tow[i][j] = 0
                    tt = n - 1
                    while tow[num][tt] != 0:
                        tt -= 1
                    tow[num][tt] = temp
                #if flag == 1: break
            if flag == 1: break
        #print(tow)

        for i in range(3):
            for j in range(n):
                if tow[i][j]:
                    stddraw.line(t**n * (i + 0.5) - tow[i][j] / 2, n - j,
                                 t**n * (i + 0.5) + tow[i][j] / 2, n - j)
                    #print(i,j,'||||',t**n*(i+0.5)-tow[i][j]/2,n-j,t**n*(i+0.5)+tow[i][j]/2,n-j)
        stddraw.show(DT)
예제 #15
0
def main(argv):
    var = float(argv[1])
    n = int(argv[2])
    stddraw.createWindow()
    stddraw.clear()
    stddraw.setXscale(-1, +1)
    stddraw.setYscale(-1, +1)
    midpoint(0, 0, 0, 0, var / math.sqrt(2), n)
    stddraw.wait()
예제 #16
0
def TukeyPlot(b=[]):
    stddraw.setXscale(0, 6)
    stddraw.setYscale(b[2] - 1, b[3] + 1)
    stddraw.line(3, b[2], 3, b[3])  #绘制中线
    x = [2, 4, 4, 2]
    ly = b[0] - b[1]
    hy = b[0] + b[1]
    y = [hy, hy, ly, ly]
    stddraw.polygon(x, y)
예제 #17
0
def main(argv):
    var = float(argv[1])
    n = int(argv[2])
    stddraw.createWindow()
    stddraw.clear()
    stddraw.setXscale(-1, +1)
    stddraw.setYscale(-1, +1)
    midpoint(0, 0, 0, 0, var / math.sqrt(2), n)
    stddraw.wait()
예제 #18
0
def main():

    hurst_ex = float(sys.argv[1])
    scale = 2**(2 * hurst_ex)
    fill_brownian(array, i, i1, variance, scale)
    stddraw.setYscale(-1, 1)
    stddraw.setXscale(0, len(array))
    stddraw.setPenRadius(0.0)
    stdstats.plotLines(array)
    stddraw.show()
예제 #19
0
def main():
    stddraw.setPenRadius(0)
    stddraw.setXscale(-3, +3)
    stddraw.setYscale(-3, +3)
    variance = 3
    hurst_exponent = 0.76
    scale_factor = 2 ** (2.0 * hurst_exponent)
    n = 13
    curve(0, 0, 0, 0, variance, scale_factor, n)
    stddraw.show()
예제 #20
0
def draw(a, which):
    #print(a)
    m = len(a)
    n = len(a[0])
    scale_length = max(m, n)
    stddraw.setXscale(-.5, scale_length)
    stddraw.setYscale(-.5, scale_length)
    for i in range(m):
        for j in range(n):
            if a[i][j] == which:
                stddraw.filledSquare(j, m - i - 1, .49)
예제 #21
0
def drawbcs(p):
    stddraw.setXscale(-1, 100)
    stddraw.setYscale(0, 5)
    x = 1
    stddraw.filledRectangle(0, 0, 0.5, 2)  #左护栏
    for t in p:
        print(t)
        drawbc(x, t)
        x += 5
    stddraw.filledRectangle(x, 0, 0.5, 2)  #右护栏
    stddraw.show()
예제 #22
0
def _init_canvas(minX, maxX, minY, maxY):
    """
    @param minX: smallest x value
    @param maxX: largest x value
    @param minY: smallest y value
    @param maxY: largest y value
    Initialises a canvas with given scale
    """
    stddraw.clear(color.DARK_GRAY)
    stddraw.setXscale(minX - 1, maxX + 1)  # -4 bis 3
    stddraw.setYscale(minY - 1, maxY + 1)  # -1 bis 8
예제 #23
0
def main(argv):
    n = int(argv[1])  # number of discs

    # Set size of window and sale
    stddraw.createWindow(4 * WIDTH, (n + 3) * HEIGHT)
    stddraw.setXscale(-1, 3)
    stddraw.setYscale(0, n + 3)

    # Solve the Towers of Hanoi with N discs
    hanoi(n)

    stddraw.wait()
예제 #24
0
def main(argv):
    n = int(argv[1])   # number of discs
    
    # Set size of window and sale
    stddraw.createWindow(4*WIDTH, (n+3)*HEIGHT)
    stddraw.setXscale(-1, 3)
    stddraw.setYscale(0, n+3)

    # Solve the Towers of Hanoi with N discs
    hanoi(n)

    stddraw.wait()
예제 #25
0
def draw(N):

    d.setXscale(0, N)
    d.setYscale(0, N)
    for i in range(N):
        for j in range(N):
            if ((i + j) % 2) != 0:
                d.setPenColor(d.BLACK)
            else:
                d.setPenColor(d.RED)
            d.filledSquare(i + .5, j + .5, .5)
            d.show(0)
예제 #26
0
def main():
    w = stdio.readInt()
    h = stdio.readInt()
    stddraw.setCanvasSize(w, h)
    stddraw.setXscale(0, w)
    stddraw.setYscale(0, h)
    stddraw.setPenRadius(.005)
    while not stdio.isEmpty():
        x = stdio.readFloat()
        y = stdio.readFloat()
        p = Point(x, y)
        p.draw()
    stddraw.show()
예제 #27
0
def canvas():
    # set the dimensions of the game grid
    global grid_h, grid_w
    grid_h, grid_w = 18, 12
    # set the size of the drawing canvas
    canvas_h, canvas_w = 40 * grid_h, 60 * grid_w
    stddraw.setCanvasSize(canvas_w, canvas_h)
    # set the scale of the coordinate system
    stddraw.setXscale(-0.5, grid_w + 4.5)
    stddraw.setYscale(-0.5, grid_h - 0.5)

    # display a simple menu before opening the game
    display_game_menu(grid_h, grid_w + 5)
예제 #28
0
def main():  # Test method

    grid_h, grid_w = 18, 12
    # set the size of the drawing canvas
    canvas_h, canvas_w = 40 * grid_h, 60 * grid_w
    stddraw.setCanvasSize(canvas_w, canvas_h)
    # set the scale of the coordinate system
    stddraw.setXscale(-0.5, grid_w + 4.5)
    stddraw.setYscale(-0.5, grid_h - 0.5)

    obj = Tile(Point(2, 4))
    obj.draw()
    stddraw.show()
    pass
예제 #29
0
def main():
    # Refresh rate (in seconds) for the keyboard.
    KEYBOARD_REFRESH_DELAY = 0.01

    # Specifies superposition window size.
    SUPERPOSITION_RANGE = 2

    # Setup the canvas and scale for the keyboard.
    stddraw.setCanvasSize(1056, 300)
    stddraw.setXscale(0, 1056)
    stddraw.setYscale(0, 300)

    # Create guitar strings for notes corresponding to the keys in keyboard.
    keyboard = 'q2we4r5ty7u8i9op-[=zxdcfvgbnjmk,.;/\' '
    notes = []
    for i in range(len(keyboard)):
        hz = 440 * 2**((i - 24.0) / 12.0)
        notes += [guitar_string.create(hz)]

    pressed = -1  # index of the pressed key
    start = time.clock()  # for refreshing the keyboard
    while True:
        # Check if the user has typed a key; if so, process it, ie, pluck
        # the corresponding string.
        if stddraw.hasNextKeyTyped():
            key = stddraw.nextKeyTyped()
            if key in keyboard:
                pressed = index(keyboard, key)
                guitar_string.pluck(notes[pressed])

        if pressed != -1:
            # Superimpose samples for keys that are within the
            # 2 * SUPERPOSITION_RANGE window centered at the pressed key.
            sample = 0.0
            b = max(0, pressed - SUPERPOSITION_RANGE)
            e = min(len(keyboard) - 1, pressed + SUPERPOSITION_RANGE)
            for i in range(b, e + 1):
                note = notes[i]
                sample += guitar_string.sample(note)
                guitar_string.tic(note)

            # Play the sample on standard audio.
            stdaudio.playSample(sample)

        # Display the keyboard with the pressed key in red, every
        # KEYBOARD_REFRESH_DELAY seconds.
        if time.clock() - start > KEYBOARD_REFRESH_DELAY:
            start = time.clock()
            draw_keyboard(pressed)
            stddraw.show(0.0)
예제 #30
0
def average_step(number):
    '''
    This function calculate the average_steps take to achieve that distance from (x_bar,y_bar) to all vertices are <=0.001

    '''
    stddraw.setXscale(-70,70)
    stddraw.setYscale(-70,70)
    stddraw.setPenRadius(0.001)
    k=[]
    for i in range(100):
        k.append(computation(number))

    stddraw.clear()
    step=average(k)
    return step
예제 #31
0
def initialize(karel_world):
    """

    :param karel_world: World object that this module can draw
    :return: None
    """
    global _cell_size
    global _font_size_small
    global _font_size_large

    # determine a reasonable canvas cell and canvas size
    na = karel_world.num_avenues
    ns = karel_world.num_streets
    _cell_size = _calculate_cell_size(na, ns)
    cell_dimensions = (_cell_size, _cell_size)

    width = _cell_size * (na + 2) + _cell_size // 2
    height = _cell_size * ns + (3 * _cell_size) // 4
    stddraw.setCanvasSize(int(width), int(height))

    stddraw.setXscale(-0.5, float(na) + 2.0)
    stddraw.setYscale(-0.5, float(ns) + 0.25)

    # choose a reasonable font size
    _font_size_small = max(_cell_size // 4, 8)
    _font_size_large = max(_cell_size // 3, 11)

    # print('cell size is', _cell_size)
    # print('font size is', _font_size_small)

    # create and scale a Picture object for a beeper
    global _beeper_picture
    _beeper_picture = Picture(constants.beeper_image_file(_cell_size))
    surface = _beeper_picture._surface
    _beeper_picture._surface = pygame.transform.scale(surface, cell_dimensions)

    # create and scale a Picture object for Karel's error state
    global _error_picture
    _error_picture = Picture(constants.error_image_file())
    surface = _error_picture._surface
    _error_picture._surface = pygame.transform.scale(surface, cell_dimensions)

    # create, scale, and rotate Picture objects for each of Karel's directions
    for angle in [90, 0, 270, 180]:
        pic = Picture(constants.karel_image_file(_cell_size))
        pic._surface = pygame.transform.scale(pic._surface, cell_dimensions)
        pic._surface = pygame.transform.rotate(pic._surface, angle)
        _karel_pictures.append(pic)
예제 #32
0
def main():
    sh = []
    ch = []
    x = -5
    while x < 5:
        sh.append(sinh(x))
        ch.append(cosh(x))
        x += 0.2
    y = max(max(sh), max(ch))
    print(sh)
    print(ch)
    print(y)
    stddraw.setYscale(-y, y)
    stdstats.plotPoints(sh)
    stdstats.plotLines(ch)
    stddraw.show()
예제 #33
0
 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)
예제 #34
0
 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)
예제 #35
0
def main():

    WIDTH = 200  # Width of largest disc
    HEIGHT = 15  # Height of each disc

    n = int(sys.argv[1])  # number of discs

    # Set size of window and sale
    stddraw.setCanvasSize(4 * WIDTH, (n + 3) * HEIGHT)
    stddraw.setXscale(-1, 3)
    stddraw.setYscale(0, n + 3)

    # Solve the Towers of Hanoi with n discs
    hanoi(n)

    stddraw.show()
예제 #36
0
def main():
    stddraw.createWindow()
    stddraw.setXscale(0, 15)
    stddraw.setYscale(0, 15)
    for i in range(16):
        for j in range (16):
            #val = i + 16*j
            val = 8*i + 8*j
            #c1 = color.Color(0, 0, 255-val)
            c1 = color.Color(255-val, 255-val, 255)            
            c2 = color.Color(val, val, val)
            stddraw.setPenColor(c1)
            stddraw.filledSquare(i, j, 0.5)
            stddraw.setPenColor(c2)
            stddraw.filledSquare(i, j, 0.25)
            stddraw.show()
    stddraw.wait()
예제 #37
0
    def __init__(self):

        self._N = stdio.readInt()         # Number of bodies
        self._radius = stdio.readFloat()  # Radius of universe

        # the set scale for drawing on screen
        stddraw.setXscale(-self._radius, +self._radius)
        stddraw.setYscale(-self._radius, +self._radius)

        # read in the _N bodies
        self.orbs = []  # Array of bodies
        for i in range(self._N):
            rx   = stdio.readFloat()
            ry   = stdio.readFloat()
            vx   = stdio.readFloat()
            vy   = stdio.readFloat()
            mass = stdio.readFloat()
            position = [ rx, ry ]
            velocity = [ vx, vy ]
            r = vector.Vector(position)
            v = vector.Vector(velocity)
            self.orbs += [body.Body(r, v, mass)]
예제 #38
0
def main(argv):

    n = int(argv[1])
    t = int(argv[2])
    stddraw.createWindow()
    stddraw.setYscale(0, 0.2)

    freq = [0] * (n+1)
    for t in range(t):
        freq[binomial(n)] += 1

    norm = [0.0] * (n+1)
    for i in range(n+1):
        norm[i] = float(freq[i]) / float(t)
    stdstats.plotBars(norm)

    stddev = math.sqrt(n) / 2.0
    phi = [0.0] * (n+1)
    for i in range(n+1):
        phi[i] = gaussian.phi(i, n/2.0, stddev)

    stdstats.plotLines(phi)
    stddraw.show()
    stddraw.wait()
예제 #39
0
#-----------------------------------------------------------------------
# plotfilter.py
#-----------------------------------------------------------------------

import stdio
import stddraw

# Plot the points read from standard input.

x0 = stdio.readFloat()
y0 = stdio.readFloat()
x1 = stdio.readFloat()
y1 = stdio.readFloat()

stddraw.createWindow()
stddraw.setXscale(x0, x1)
stddraw.setYscale(y0, y1)
stddraw.setPenRadius(0.001)

# Read and plot the points.
while not stdio.isEmpty():
    x = stdio.readFloat()
    y = stdio.readFloat()
    stddraw.point(x, y)

stddraw.show()
stddraw.wait()
예제 #40
0
# 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)))
stdstats.plotBars(norm)
stdstats.plotLines(phi)
stddraw.show()

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

# python bernoulli.py 20 100000

예제 #41
0
 def draw(self):
     stddraw.setYscale(0, self._max)
     stdstats.plotBars(self._freq)
예제 #42
0
# oscilloscope.py
#-----------------------------------------------------------------------

# Simulate the output of an oscilloscope. Assume that the vertical and
# horizontal inputs are sinusoidal. Use these equations:

#    x = A sin (wX + phiX)
#    y = B sin (wY + phiY)

import stddraw
import sys
import math

stddraw.createWindow()
stddraw.setXscale(-1, +1)
stddraw.setYscale(-1, +1)
stddraw.setPenRadius(0)

A    = float(sys.argv[1])    # amplitudes
B    = float(sys.argv[2])
wX   = float(sys.argv[3])    # angular frequencies
wY   = float(sys.argv[4])
phiX = float(sys.argv[5])    # phase factors
phiY = float(sys.argv[6])

# Convert from degrees to radians.
phiY = math.radians(phiX)
phiY = math.radians(phiY)

t = 0.0
while True:
예제 #43
0
#-----------------------------------------------------------------------
# checkerboard.py
#-----------------------------------------------------------------------

import stddraw
import sys

# Accept integer command-line argument n. Draw an n-by-n checkerboard.

n = int(sys.argv[1])
stddraw.createWindow()

stddraw.setXscale(0, n)
stddraw.setYscale(0, n)

for i in range(n):
    for j in range(n):
        if ((i + j) % 2) != 0:
            stddraw.setPenColor(stddraw.BLACK)
        else:
            stddraw.setPenColor(stddraw.RED)
        stddraw.filledSquare(i + .5, j + .5, .5)
        stddraw.show()

stddraw.wait()
예제 #44
0
# Accept integers r1, g1, b1, r2, g2, and b2 as command-line arguments.
# Draw to standard draw Albers squares using colors (r1, g1, b1) and
# (r2, g2, b2).

r1 = int(sys.argv[1])
g1 = int(sys.argv[2])
b1 = int(sys.argv[3])
c1 = color.Color(r1, g1, b1)

r2 = int(sys.argv[4])
g2 = int(sys.argv[5])
b2 = int(sys.argv[6])
c2 = color.Color(r2, g2, b2)

stddraw.setCanvasSize(512, 256)
stddraw.setYscale(.25, .75)

stddraw.setPenColor(c1)
stddraw.filledSquare(.25, .5, .2)

stddraw.setPenColor(c2)
stddraw.filledSquare(.25, .5, .1)

stddraw.setPenColor(c2)
stddraw.filledSquare(.75, .5, .2)

stddraw.setPenColor(c1)
stddraw.filledSquare(.75, .5, .1)

stddraw.show()
예제 #45
0
#-----------------------------------------------------------------------
# banner.py
#-----------------------------------------------------------------------

import stddraw
import sys

# Accept string command-line argument s. Draw s, and move it across
# the screen, left-to-right, wrapping around when it reaches the border.

s = sys.argv[1]

# Remove the 5% border.
stddraw.createWindow()
stddraw.setXscale(1.0/22.0, 21.0/22.0)
stddraw.setYscale(1.0/22.0, 21.0/22.0)

# Set the font.
stddraw.setFontFamily('Arial') 
stddraw.setFontSize(60)
stddraw.setPenColor(stddraw.BLACK)

i = 0.0
while True:
    stddraw.clear()
    stddraw.text((i % 1.0),       0.5, s)
    stddraw.text((i % 1.0) - 1.0, 0.5, s)
    stddraw.text((i % 1.0) + 1.0, 0.5, s)
    stddraw.sleep(60)
    stddraw.show()
    i += 0.01
예제 #46
0
# at time t is
#
# x = (R+r)*cos(t) - (r+a)*cos(((R+r)/r)*t)
# y = (R+r)*sin(t) - (r+a)*sin(((R+r)/r)*t)
 
# Credits: idea suggested by Diego Nehab
# Reference: http://www.math.dartmouth.edu/~dlittle/java/SpiroGraph
# Reference: http://www.wordsmith.org/~anu/java/spirograph.html

R = float(sys.argv[1])
r = float(sys.argv[2])
a = float(sys.argv[3])

stddraw.createWindow()
stddraw.setXscale(-300, +300)
stddraw.setYscale(-300, +300)
stddraw.setPenRadius(0)

t = 0.0
while True:
    x = (R+r) * math.cos(t) - (r+a) * math.cos(((R+r)/r)*t)
    y = (R+r) * math.sin(t) - (r+a) * math.sin(((R+r)/r)*t)
    degrees = -math.degrees((R+r)/r)*t
    stddraw.point(x, y)
    #stddraw.picture(x, y, "earth.gif", degrees)
    #stddraw.rotate(+Math.toDegrees((R+r)/r)*t)
    stddraw.sleep(10)
    stddraw.show()
    t += 0.01

# Example executions:
# 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.
        sum += p[page][j]
        if r < sum:
            page = j
            break
    freq[page] += 1
예제 #48
0
import stddraw

# Draw a bouncing ball to standard draw.

RADIUS = .05
DT = 20.0

stddraw.setXscale(-1.0, 1.0)
stddraw.setYscale(-1.0, 1.0)

rx = .480
ry = .860
vx = .015
vy = .023

while True:
    # Update ball position and draw it there.
    if abs(rx + vx) + RADIUS > 1.0:
        vx = -vx
    if abs(ry + vy) + RADIUS > 1.0:
        vy = -vy
    rx = rx + vx
    ry = ry + vy

    stddraw.clear(stddraw.GRAY)
    stddraw.filledCircle(rx, ry, RADIUS)
    stddraw.show(0)
예제 #49
0
 def draw(self):
     stddraw.setYscale(0, max(self._freqCounts))
     stdstats.plotBars(self._freqCounts)
예제 #50
0
def main():

    stddraw.createWindow(1024, 256)
    stddraw.setPenRadius(0)
    stddraw.setXscale(0, _SAMPLES_PER_REDRAW)
    stddraw.setYscale(-0.75, +0.75)
    stddraw.show()

    # Create keyboardDict, a dictionary relating each keyboard key
    # to a guitar string.
    keyboardDict = {}
    i = 0
    for key in _KEYBOARD:
        factor = 2 ** ((i - 24) / 12.0)
        guitarString = guitarstring.GuitarString(_CONCERT_A * factor)
        keyboardDict[key] = guitarString
        i += 1

    # pluckedGuitarStrings is the set of all guitar strings that have
    # been plucked.
    pluckedGuitarStrings = set()

    t = 0

    # The main input loop.
    while True:

        if stddraw.hasNextKeyTyped():

            # Fetch the key that the user just typed.
            key = stddraw.nextKeyTyped()

            # Figure out which guitar string to pluck, and pluck it.
            try:
                guitarString = keyboardDict[key]
                guitarString.pluck()
                pluckedGuitarStrings.add(guitarString)
            except KeyError:
                pass

        # Add up the samples from each plucked guitar string. Also
        # advance the simulation of each plucked guitar string by
        # one step.
        sample = 0.0
        faintGuitarStrings = set()
        for guitarString in pluckedGuitarStrings:
            sample += guitarString.sample()
            guitarString.tic()
            if guitarString.isFaint():
                faintGuitarStrings.add(guitarString)

        # Remove faint guitar strings from the set of plucked guitar
        # strings.
        for guitarString in faintGuitarStrings:
            pluckedGuitarStrings.remove(guitarString)

        # Play the total.
        stdaudio.playSample(sample)

        # Plot
        stddraw.point(t % _SAMPLES_PER_REDRAW, sample)

        if t == (_SAMPLES_PER_REDRAW - 1):
            stddraw.show()
            stddraw.clear()
            t = 0

        t += 1
예제 #51
0
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()
예제 #52
0
파일: koch.py 프로젝트: davidhuizhou/python
        myTurtle.goForward(stepSize)
        return  
    koch(n-1, stepSize, myTurtle)
    myTurtle.turnLeft(60.0)
    koch(n-1, stepSize, myTurtle)
    myTurtle.turnLeft(-120.0)
    koch(n-1, stepSize, myTurtle)
    myTurtle.turnLeft(60.0)
    koch(n-1, stepSize, myTurtle)
 
# Accept integer n as a command-line argument. Plot a Koch curve of 
# order n to standard draw.

n = int(sys.argv[1])
stddraw.setCanvasSize(512, 256)
stddraw.setYscale(-.1, 0.4)
stddraw.setPenRadius(0.0)
stddraw.clear(stddraw.LIGHT_GRAY)
stepSize = 1.0 / (3.0 ** n)
myTurtle = Turtle(0.0, 0.0, 0.0)
koch(n, stepSize, myTurtle)
stddraw.show()

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

# python koch.py 0

# python koch.py 1

# python koch.py 2
예제 #53
0
# Create a RandomQueue object containing Queue objects.
servers = RandomQueue()
for i in range(serverCount):
    servers.enqueue(Queue())

for j in range(itemCount):
    # Assign an item to a server.
    best = servers.sample()
    for k in range(1, sampleSize):
        # Pick a random server, update if new best.
        queue = servers.sample()
        if len(queue) < len(best):
            best = queue
    # best is the shortest server queue.
    best.enqueue(j)

lengths = []
while not servers.isEmpty():
    lengths += [len(servers.dequeue())]
stddraw.clear(stddraw.LIGHT_GRAY)
stddraw.setYscale(0, 2.0 * itemCount / serverCount)
stdstats.plotBars(lengths)
stddraw.show()

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

# python loadbalance.py 50 500 1

# python loadbalance.py 50 500 2
예제 #54
-1
def main(argv):

    fileName = argv[1]
    w = int(argv[2])
    h = int(argv[3])

    source = picture.Picture()
    source.load(fileName)

    target = picture.Picture(w, h)

    for ti in range(w):
        for tj in range(h):
            si = ti * source.width() // w
            sj = tj * source.height() // h
            target.set(ti, tj, source.get(si, sj))

    maxHeight = max(source.height(), target.height())

    stddraw.createWindow(source.width() + target.width(), maxHeight)
    stddraw.setXscale(0, source.width() + target.width())
    stddraw.setYscale(0, maxHeight)

    stddraw.picture(source, source.width() / 2, maxHeight / 2)
    stddraw.picture(target, source.width() + target.width() / 2, maxHeight / 2)

    stddraw.show()
    stddraw.wait()