def _loadFromJpgFile(self, f): """ Change 'self' by reading from the JPG file whose name is 'f'. """ try: from PIL import Image image = Image.open(f) maxW, maxH = image.size self._photoImage = \ Tkinter.PhotoImage(width=maxW, height=maxH) self._buffer = \ stdarray.create2D(maxW, maxH, str(color.BLACK)) for w in range(maxW): for h in range(maxH): r, g, b = image.getpixel((w, h)) c = color.Color(r, g, b) self._buffer[w][h] = str(c) self._isDirty = True except ImportError: import pygame surface = pygame.image.load(f) maxW = surface.get_width() maxH = surface.get_height() self._photoImage = \ Tkinter.PhotoImage(width=maxW, height=maxH) self._buffer = \ stdarray.create2D(maxW, maxH, str(color.BLACK)) for w in range(maxW): for h in range(maxH): r, g, b, a = tuple(surface.get_at((w, h))) c = color.Color(r, g, b) self._buffer[w][h] = str(c) self._isDirty = True
def flow(isOpen): m = len(isOpen) n = len(isOpen[0]) isFull = stdarray.create2D(m, n, False) for j in range(n): _flow(isOpen, isFull, 0, j) return isFull
def __init__(self, picture, tau): """ Constructs a blob finder to find blobs in the picture pic,using of threshold tau """ self.tau = tau self.photo = picture # create a array with picture size check = stdarray.create2D(self.photo.height(), self.photo.width(), False) # list of blobs self.blobs = [] # Modifies RGB photos for i in range(self.photo.height()): for j in range(self.photo.width()): color = self.photo.get(j, i) r = color.getRed() g = color.getGreen() b = color.getBlue() if r >= self.tau and g >= self.tau and b >= self.tau: check[i][j] = True for i in range(self.photo.height()): for j in range(self.photo.width()): if check[i][j]: blob = Blob() self.proccess(blob, check, i, j) self.blobs.append(blob)
def flow(open): n = len(open) full = stdarray.create2D(n, n, False) # Percolation flow computation goes here. for j in range(n): flowHelp(open, full, 0, j) return full
def __init__(self, maxW=_DEFAULT_SIZE, maxH=_DEFAULT_SIZE): """ Construct 'self' such that it is all black with width 'maxW' and height 'maxH'. """ if _count == 0: _background = pygame.display.set_mode([w, h + 50]) self._photoImage = pygame.Surface((w, h)) self._photoImage.fill(pygameColor(BLACK)) else: self._photoImage = pygame.Surface((w, h)) count += 1 self._photoImage = None self._buffer = None self._isDirty = None self._toplevel = None self._label = None self._photoImage = \ Tkinter.PhotoImage(width=maxW, height=maxH) self._buffer = \ stdarray.create2D(maxW, maxH, str(color.BLACK)) self._isDirty = True
def __init__(self, pic, tau): """ Constructs a blob finder to find blobs in the picture pic, using a luminance threshold tau. """ # Initialize an empty list for the blobs in pic. self._blobs = [] # Create a 2D list of booleans called marked, having the same # dimensions as pic. x = pic.width() y = pic.height() marked = stdarray.create2D(x, y, False) # Enumerate the pixels of pic, and for each pixel (i, j): for i in range(x): for j in range(y): # 1. Create a Blob object called blob. blob = Blob() # 2. Call _findBlob() with the right arguments. self._findBlob(pic, tau, i, j, marked, blob) # 3. Add blob to _blobs if it has a non-zero mass. if blob.mass() > 0: self._blobs.append(blob)
def flow(isOpen): n = len(isOpen) isFull = stdarray.create2D(n, n, False) for j in range(n): global depth depth = 0 _flow(isOpen, isFull, 0, j) print('depth:', depth) return isFull
def flow(isOpen): n = len(isOpen) isFull = stdarray.create2D(n, n, False) for j in range(n): isFull[0][j] = isOpen[0][j] for i in range(1, n): for j in range(n): if isOpen[i][j] and isFull[i-1][j]: isFull[i][j] = True return isFull
def flow(isOpen): n = len(isOpen[0]) isFull = stdarray.create2D(n, n, False) #出于好意,填上第一行,其实并没什么用,从第二行开始算起 for j in range(n): _flow(isOpen, isFull, 0, j) #真正的渗透,从第二行开始 for j in range(n): _flow(isOpen, isFull, 1, j) return isFull
def flow(open): n = len(open) full = stdarray.create2D(n, n, False) # Percolation flow computation goes here. for j in range(n): full[0][j] = open[0][j] for i in range(1, n): for j in range(n): full[i][j] = open[i][j] and full[i-1][j] return full
def random(n, p): a = stdarray.create2D(n, n, False) for i in range(n): for j in range(n): a[i][j] = stdrandom.bernoulli(p) #方格的横线比竖线少一 for i in range(0, n, 2): for j in range(int((n - 1) / 2), n): a[i][j] = False return a
def disc_turn(current_move): turn_array = stdarray.create2D(m, split_moves, 0) for i in range(0, m): for j in range(0, split_moves): plug = int(((2 ** (i + 1)) * ((j + 1) - 0.5))) turn_array[i][j] = int(plug) for i in range(0, m): for j in range(0, split_moves): if turn_array[i][j] == current_move: disc_turn = int(i + 1) return (int(disc_turn))
def living(isAlive): n = len(isAlive) toAlive = stdarray.create2D(n, n, False) for i in range(n): for j in range(n): if isAlive[i][j]: aliveRule(isAlive,toAlive,i,j) else: deadRule(isAlive,toAlive,i,j) # for j in range(n): # _living(isAlive, toAlive, 0, j) return toAlive
def had(n): H = stdarray.create2D(n, n, True) # Initialize Hadamard matrix of order n. i1 = 1 while i1 < n: for i2 in range(i1): for i3 in range(i1): H[i2 + i1][i3] = H[i2][i3] H[i2][i3 + i1] = H[i2][i3] H[i2 + i1][i3 + i1] = not H[i2][i3] i1 += i1 return H
def transpose(m): rowCount = len(m) colCount = len(m[0]) if rowCount != colCount: raise Exception('row count must equal col count') transposeMatrix = stdarray.create2D(rowCount, colCount, 0.0) for row in range(rowCount): for col in range(colCount): transposeMatrix[col][row] = m[row][col] return transposeMatrix
def creat_an_useful_array(): useful = True game_array = stdarray.create2D(9, 7, 1) while useful or useful2: for i in range(9): for k in range(7): game_array[i][k] = random.randrange(0, 6) useful = the_array_can_be_used(game_array) useful2 = the_array_can_be_used2(game_array) return game_array
def subtract(m1, m2): rowCount = len(m1) colCount = len(m1[0]) if rowCount != len(m2): raise Exception('m1 row count must equal m2 row count') if colCount != len(m2[0]): raise Exception('m1 col count must equal m2 col count') diff = stdarray.create2D(rowCount, colCount, 0.0) for row in range(rowCount): for col in range(colCount): diff[row][col] = m1[row][col] - m2[row][col] return diff
def add(m1, m2): rowCount = len(m1) colCount = len(m1[0]) if rowCount != len(m2): raise Exception('m1 row count must equal m2 row count') if colCount != len(m2[0]): raise Exception('m1 col count must equal m2 col count') total = stdarray.create2D(rowCount, colCount, 0.0) for row in range(rowCount): for col in range(colCount): total[row][col] = m1[row][col] + m2[row][col] return total
def transpose(a): # Get the dimensions of matrix a. m = len(a[0]) n = len(a) # Create an n-by-m matrix c with all elements initialized to 0.0. c = stdarray.create2D(m, n, 0.0) # Fill in the elements of c such that c[i][j] = a[j][i]. for i in range(m): for j in range(n): c[i][j] = a[j][i] # Return c. return c
def multiplyMM(m1, m2): m1RowCount = len(m1) m1ColCount = len(m1[0]) m2RowCount = len(m2) m2ColCount = len(m2[0]) if m1ColCount != m2RowCount: raise Exception('m1 col count must equal m2 row count') prod = stdarray.create2D(m1RowCount, m2ColCount, 0.0) for i in range(m1RowCount): for j in range(m2ColCount): for k in range(m1ColCount): prod[i][j] += m1[i][k] * m2[k][j] return prod
def __init__(self, maxW=_DEFAULT_SIZE, maxH=_DEFAULT_SIZE): """ Construct 'self' such that it is all black with width 'maxW' and height 'maxH'. """ self._photoImage = None self._buffer = None self._isDirty = None self._toplevel = None self._label = None self._photoImage = \ Tkinter.PhotoImage(width=maxW, height=maxH) self._buffer = \ stdarray.create2D(maxW, maxH, str(color.BLACK)) self._isDirty = True
def transpose(a): # Get the dimensions of matrix a. m = len(a) # number of rows in a n = len(a[0]) # number of columns in a # Create an n-by-m matrix c with all elements initialized # to 0.0. c = stdarray.create2D(n, m, 0.0) # Fill in the elements of c such that c[i][j] = a[j][i], # where 0 <= i < n and 0 <= j < m. for i in range(0, n): for j in range(0, m): c[i][j] = a[j][i] # Return c. return c
def _loadFromGifFile(self, f): """ Change 'self' by reading from the GIF file whose name is 'f'. """ self._photoImage = Tkinter.PhotoImage(file=f) maxW = self._photoImage.width() maxH = self._photoImage.height() self._buffer = stdarray.create2D(maxW, maxH, None) for w in range(maxW): for h in range(maxH): colorStr = self._photoImage.get(w, h) colorList = colorStr.split() r = int(colorList[0]) g = int(colorList[1]) b = int(colorList[2]) c = color.Color(r, g, b) self._buffer[w][h] = str(c) self._isDirty = False
def __init__(self, pic, tau): """ Constructs a blob finder to find blobs in the picture pic, using a luminance threshold tau. """ # set the blobs list self._blobs = [] # Create a 2D array list with booleans List = stdarray.create2D(pic.width(), pic.height(), False) # Enumerate the pixels of pics for i in range(pic.width()): for j in range(pic.height()): blob = Blob() self._findBlob(pic, tau, i, j, List, blob) if blob.mass() > 0: self._blobs.append(blob)
def __init__(self, pic, tau): """ Constructs a blob finder to find blobs in the picture pic, using a luminance threshold tau. """ # Initialize an empty list for the blobs in pic. self._blobs = [] # Create a 2D list of booleans called marked, having the same # dimensions as pic. marked = stdarray.create2D(pic.width(), pic.height(), False) for i in range(pic.width()): for j in range(pic.height()): b = Blob() self.Blobfinder(pic, tau, i, j, marked, b) if b.mass() > 0: self._blobs += [b]
def flow(isOpen): n = len(isOpen) isFull = stdarray.create2D(n, n, False) stddraw.setPenColor(stddraw.BLUE) for j in range(n): isFull[0][j] = isOpen[0][j] percolationio.draw(isFull, True) stddraw.show(50.0) for i in range(1, n): for j in range(n): if isOpen[i][j] and isFull[i-1][j]: isFull[i][j] = True percolationio.draw(isFull, True) stddraw.show(50.0) # for j in range(n): # if isOpen[i][j]: # if 1 <= j and j < n-1: # if isFull[i][j-1] or isFull[i][j+1]: # isFull[i][j] = True # percolationio.draw(isFull, True) # stddraw.show(50.0) isFull = horizontal(isOpen,isFull,i) return isFull
def right(): if moves < 0 and score < winning_score: stddraw.text(5.2, 10.5, "You lose!") stddraw.show() elif score > winning_score: stddraw.text(5.2, 10.5, "You win!") stddraw.show() while game_over(): if turns == 1 and stddraw.mousePressed(): a = stdarray.create2D(9, 7, 0) select_first(a) first_position = select_first_position() right() if turns == 2 and stddraw.mousePressed(): select_second(a) score = juweimodule.creat_a_new_useful_game(game_board, score) print_remaining_moves() right() stddraw.show(15) stddraw.setFontSize(28) stddraw.setPenColor(stddraw.BLUE) # python3 lanjin_client.py
def random(n, p): a = stdarray.create2D(n, n, False) for i in range(n): for j in range(n): a[i][j] = stdrandom.bernoulli(p) return a
import random # Accept an integer moves as a command-line argument. Read a # transition matrix from standard input. Perform moves moves as # prescribed by the transition matrix, and write to standard output # the relative frequency of hitting each page. 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]
def flow(isOpen): n = len(isOpen) isFull = stdarray.create2D(n, n, False) for j in range(n): _flow(isOpen, isFull, 0, j) return isFull
#----------------------------------------------------------------------- # 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.
def __init__(self, m=1024): self._m = m self._keys = stdarray.create2D(m, 0) self._vals = stdarray.create2D(m, 0)
"""Dot product of 2 rectangular matrices. The number of columns in the first matrix must be equal to the number of rows in the second matrix""" import sys import stdarray import stdio import random import math m = 3 n = 4 a = stdarray.create2D(m, n, 0) for i in range(m): for t in range(n): a[i][t] = random.randrange(1, 10) stdio.writeln(a) t = 4 p = 3 b = stdarray.create2D(t, p, 0) for r in range(t): for j in range(p): b[r][j] = random.randrange(1, 10) stdio.writeln(b) if n == t and m == p: q = m c = stdarray.create2D(q, q, 0) for i in range(q): for j in range(q): for k in range(n): c[i][j] += a[i][k] * b[k][j]
#----------------------------------------------------------------------- # 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.
# 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): # Move random walker i. r = random.randrange(0, 4) if r == 0: x[i] += 1 elif r == 1: x[i] -= 1 elif r == 2:
import stdarray import sys import random # Accept integers n and trialCount as command-line arguments. Do # trialCount random self-avoiding walks in an n-by-n lattice. # Write to standard output the percentage of dead ends encountered. n = int(sys.argv[1]) trials = int(sys.argv[2]) deadEnds = 0 for t in range(trials): # Create an n-by-n array, with all elements set to False. a = stdarray.create2D(n, n, False) x = n//2 y = n//2 while (x > 0) and (x < n-1) and (y > 0) and (y < n-1): # Check for dead end and make a random move. a[x][y] = True if a[x-1][y] and a[x+1][y] and a[x][y-1] and a[x][y+1]: deadEnds += 1 break r = random.randrange(1, 5) if (r == 1) and (not a[x+1][y]): x += 1 elif (r == 2) and (not a[x-1][y]): x -= 1 elif (r == 3) and (not a[x][y+1]):