I have following matrix:
W = [['a', 'b', 'b', 'b', 'a'],
['a', 'a', 'a', 'a', 'b'],
['a', 'b', 'a', 'b', 'b'],
['a', 'a', 'a', 'b', 'b'],
['b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b']]
If I choose W[x][y] from matrix, how can I count a-characters around that spesific point? For example let's say I choose W[4][1] which is b. I can see there is three a's around that point. But how can I determine it by coding? I ended up really messy peace of code, and realized it would not have worked if we change the dimension of matrix. Problem was also that if I choose the point near rounds, W[y-1][(x):(x+1)].count("a") -kind of thinking doesn't work.
Again, help would be appreciated! Thanks!
UPDATE:
W = [['K', ' ', ' ', ' ', ' '],
['K', 'K', 'K', 'K', ' '],
['K', ' ', 'K', ' ', ' '],
['K', 'K', 'K', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ']]
def count_matrix(W, y, x, ch="K"):
ref = (-1, 0, 1)
occ = []
a = "K"
b = " "
for dy, dx in [(a, b) for a in ref for b in ref if (a,b)!=(0, 0)]:
if (x+dx) >= 0 and (y+dy) >= 0:
try:
occ.append(W[x+dx][y+dy])
except IndexError:
pass
return occ.count(ch)
print count_matrix(W,0,0)
This returns 0.
ref = (-1, 0, -1)a='K'andb=" "is not doing what you think. Theaandbinside the list comprehension are just temp variables with namespace scope limited to the comprehension. Setting a and b to other values outside the comprehension does not change anything.