Please help me print the pattern below as it is, if the input entered is 7:
1 1 1 1 1 1 1 1 2 2 2 2 2 1 1 2 3 3 3 2 1 1 2 3 4 3 2 1 1 2 3 3 3 2 1 1 2 2 2 2 2 1 1 1 1 1 1 1 1
I figured out to find the middle element of the pattern with any input:
rows=int(input("Enter the number of rows:")) l=[] for x in range(1,rows+1): if x%2!=0: l.append(x) mid_value=len(l)
Please help me complete the above pattern…… Thanks in advance!
Advertisement
Answer
If you use a list-of-lists to store the values, the value for any specific cell can be determined by doing some basic math involving the cell indexes and the number of rows.
An illustration:
def cell_value(i, j, n_rows): # The value of any cell is the minimum distance # from its own coordinates (i, j) to the "outside" (ie, # an i or j less than 0 or equal to n_rows). Imagine an # ant in the grid. How many steps would it have to take # to escape the grid, using the shortest route? return min( abs(i - -1), abs(i - n_rows), abs(j - -1), abs(j - n_rows), ) N_ROWS = 7 rows = [ [ cell_value(i, j, N_ROWS) for j in range(N_ROWS) ] for i in range(N_ROWS) ] for r in rows: print(*r)
Output:
1 1 1 1 1 1 1 1 2 2 2 2 2 1 1 2 3 3 3 2 1 1 2 3 4 3 2 1 1 2 3 3 3 2 1 1 2 2 2 2 2 1 1 1 1 1 1 1 1