一次关于递归作业的总结(code)
from random import seed, randrange import sys dim = 10 def display_grid(): for row in grid: print(' ', *row) def display_grid1(): for row in grid1: print(' ', *row) #grid1为深度复制grid的结果,这里将两者 分别打印,方便比较结果 def one_shape(row,col,n_colour): if not (row<len(grid1[0]) and row>=0 and col>=0 and col<len(grid1)): #这里一定注意等于0的情况 return #将不满足的情况写在not后面的好处是如果不符合要求即return,不会引发error value if gride1[row][col]==1: grid1[row][col]=n_colour #如果符合条件,修改赋值 one_shape(row+1,col,n_colour) one_shape(row-1,col,n_colour) one_shape(row,col+1,n_colour) one_shape(row,col-1,n_colour) #调用递归,即不断调用当前函数,看是否满足要求 else: return for_seed,density=0,8 seed(for_seed) grid = [[int(randrange(density) != 0) for _ in range(dim)] for _ in range(dim) ] grid1=[[i for i in row] for row in grid] print('Here is the grid that has been generated:') display_grid() print(' ') one_shape(0,0,2) display_grid1() print('The maximum number of spikes of some shape is:', max_number_of_spikes(nb_of_shapes) )