本文共 2697 字,大约阅读时间需要 8 分钟。
You are given a state for a rectangular board game grid with chips in a binary matrix, where 1 is a cell with a chip and 0 is an empty cell. You are also given the coordinates for a cell in the form of row and column numbers (starting from 0). You should determine how many chips are close to this cell. Every cell interacts with its eight neighbours; those cells that are horizontally, vertically, or diagonally adjacent.
example For the given examples (see the schema) there is the same grid: ((1, 0, 0, 1, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 1), (1, 0, 0, 0, 0), (0, 0, 1, 0, 0),)For the first example coordinates of the cell is (1, 2) and as we can see from the schema this cell has 3 neighbour chips. For the second example coordinates is (0, 0) and this cell contains a chip, but we count only neighbours and the answer is 1.
Input: Three arguments. A grid as a tuple of tuples with integers (1/0), a row number and column number for a cell as integers. Output: How many neighbouring cells have chips as an integer.给定一个二维元组。输出任意坐标周围的1的个数。
def count_neighbours(grid, row, col): a=len(grid) b=len(grid[0]) rangelistx=range(0,a) rangelisty=range(0,b) countrangex=[row-1,row,row+1] countrangey=[col-1,col,col+1] newrangex=[] newrangey=[] count=0 for i in countrangex: if i in rangelistx: newrangex.append(i) for i in countrangey: if i in rangelisty: newrangey.append(i) for i in newrangex: for j in newrangey: if grid[i][j]==1: count+=1 if grid[row][col]==1: count-=1 return countif __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert count_neighbours(((1, 0, 0, 1, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 1), (1, 0, 0, 0, 0), (0, 0, 1, 0, 0),), 1, 2) == 3, "1st example" assert count_neighbours(((1, 0, 0, 1, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 1), (1, 0, 0, 0, 0), (0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example" assert count_neighbours(((1, 1, 1), (1, 1, 1), (1, 1, 1),), 0, 2) == 3, "Dense corner" assert count_neighbours(((0, 0, 0), (0, 1, 0), (0, 0, 0),), 1, 1) == 0, "Single"
元组中行x列y都有各自的取值范围。
行:在[row-1,row,row+1]范围里,如果元素在x的范围里,就newrange.append(i)加入到新的范围list里面。 对于列也一样。 然后对新的行列list遍历,每有一个1出现,count+1。 最后在判断grid[row][col]这个值本身是不是1,是的话就count-1。 return count finish!!!!转载地址:http://djvti.baihongyu.com/