Reputation: 87
I am trying to print the following pattern:
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
My python code is:
def pattern(n):
d = n + (n - 1)
l = [[0 for row in range(d)] for col in range(d)]
for a in range(0, n):
for i in range(a, d):
for j in range(a, d):
l[a][i][j].append(n)
d -= 1
n -= 1
print(pattern(3))
But I am getting the following Error:
Traceback (most recent call last):
File "test.py", line 10, in <module>
print(pattern(3))
File "test.py", line 7, in pattern
l[a][i][j].append(n)
TypeError: 'int' object is not subscriptable
Can anyone guide me how to overcome this?
Thank you in advance.
Upvotes: 0
Views: 121
Reputation: 169032
Because it's somewhat hard to understand how your code is supposed to do what it should (sorry!), here's a pretty Pythonic way to generate a matrix like this as a generator function.
def pattern(n):
size = n * 2 - 1
n_1 = n - 1
for y in range(size):
yield [max(abs(x - n_1), abs(y - n_1)) + 1 for x in range(size)]
The idea is that we look at the "distance" of the cell we're generating from n - 1
, which must be the center point of the grid (which is n * 2 - 1
items wide and tall).
As it's a generator function, you can get a list-of-lists out of it by calling e.g. list(pattern(size))
.
Here's an example program –
for size in range(1, 6):
print(size)
for row in pattern(size):
print(row)
– and its output:
1
[1]
2
[2, 2, 2]
[2, 1, 2]
[2, 2, 2]
3
[3, 3, 3, 3, 3]
[3, 2, 2, 2, 3]
[3, 2, 1, 2, 3]
[3, 2, 2, 2, 3]
[3, 3, 3, 3, 3]
4
[4, 4, 4, 4, 4, 4, 4]
[4, 3, 3, 3, 3, 3, 4]
[4, 3, 2, 2, 2, 3, 4]
[4, 3, 2, 1, 2, 3, 4]
[4, 3, 2, 2, 2, 3, 4]
[4, 3, 3, 3, 3, 3, 4]
[4, 4, 4, 4, 4, 4, 4]
5
[5, 5, 5, 5, 5, 5, 5, 5, 5]
[5, 4, 4, 4, 4, 4, 4, 4, 5]
[5, 4, 3, 3, 3, 3, 3, 4, 5]
[5, 4, 3, 2, 2, 2, 3, 4, 5]
[5, 4, 3, 2, 1, 2, 3, 4, 5]
[5, 4, 3, 2, 2, 2, 3, 4, 5]
[5, 4, 3, 3, 3, 3, 3, 4, 5]
[5, 4, 4, 4, 4, 4, 4, 4, 5]
[5, 5, 5, 5, 5, 5, 5, 5, 5]
EDIT: As requested in comments, here's a simplified version which is not a generator function and doesn't use list comprehensions:
def pattern_simple(n):
size = n * 2 - 1
n_1 = n - 1
rows = []
for y in range(size):
row = []
for x in range(size):
row.append(max(abs(x - n_1), abs(y - n_1)) + 1)
rows.append(row)
return rows
Upvotes: 4
Reputation: 148965
Just to start from your own code even if the answer is a bit late...
You code tries to build an array of 0, and then writes decreasing values in sub-array. Simply you wrongly copied it. It should be:
def pattern(n):
d = n + (n - 1)
l = [[0 for row in range(d)] for col in range(d)]
for a in range(0, n):
for i in range(a, d):
for j in range(a, d):
l[i][j]=n
n -= 1
d -= 1
return l
Upvotes: 1