Please help me print the pattern below as it is, if the input entered is 7:
JavaScript
x
8
1
1 1 1 1 1 1 1
2
1 2 2 2 2 2 1
3
1 2 3 3 3 2 1
4
1 2 3 4 3 2 1
5
1 2 3 3 3 2 1
6
1 2 2 2 2 2 1
7
1 1 1 1 1 1 1
8
I figured out to find the middle element of the pattern with any input:
JavaScript
1
7
1
rows=int(input("Enter the number of rows:"))
2
l=[]
3
for x in range(1,rows+1):
4
if x%2!=0:
5
l.append(x)
6
mid_value=len(l)
7
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:
JavaScript
1
26
26
1
def cell_value(i, j, n_rows):
2
# The value of any cell is the minimum distance
3
# from its own coordinates (i, j) to the "outside" (ie,
4
# an i or j less than 0 or equal to n_rows). Imagine an
5
# ant in the grid. How many steps would it have to take
6
# to escape the grid, using the shortest route?
7
return min(
8
abs(i - -1),
9
abs(i - n_rows),
10
abs(j - -1),
11
abs(j - n_rows),
12
)
13
14
N_ROWS = 7
15
16
rows = [
17
[
18
cell_value(i, j, N_ROWS)
19
for j in range(N_ROWS)
20
]
21
for i in range(N_ROWS)
22
]
23
24
for r in rows:
25
print(*r)
26
Output:
JavaScript
1
8
1
1 1 1 1 1 1 1
2
1 2 2 2 2 2 1
3
1 2 3 3 3 2 1
4
1 2 3 4 3 2 1
5
1 2 3 3 3 2 1
6
1 2 2 2 2 2 1
7
1 1 1 1 1 1 1
8