unicornication unicornication - 1 month ago 13
Python Question

Counting consecutive numbers in all columns of a 2D array

I have a 2d array,

X
, that looks like this

[0, 0, 0, 2, 1]
[1, 2, 1, 0, 1]
[2, 2, 1, 0, 0]
[0, 0, 1, 2, 0]


I'm trying to iterate through the entire 2D array to try and count all the instances where there are 2 consecutive elements in a column. E.g.
X
above would return 4 (
X[1][1] == X[2][1] && X[1][2] == X[2][2] && X[2][2] == X[3][2]
and so on)

I'm finding this very hard to visualize. So far I have:

def get_opposite(number):
if number == 2: return 1
if number == 1: return 2

def counter(X, number):
count = 0
for i in range(len(X)):
for j in range(len(X[i])-1):
if X[i][j] == X[i][j+1] and X[i][j] != 0 and X[i][j] != get_opposite(number):
count += 1
return count


I keep either getting vastly incorrect results, or IndexError, it should be fairly straight forward but I'm not sure what I'm doing wrong

Answer

If you compare the example you give in the text with your actual code, you'll notice your code is comparing with the value on the right, not the with the value below it. You need to apply +1 to the first index, not the second. This also means the range of your loops has to be adapted accordingly.

Secondly, you don't need the first function. The equality comparison is enough.

Also, I removed the second argument of the function, as it serves no role:

def counter(X):
    count = 0
    for i in range(len(X)-1):
        for j in range(len(X[i])):
            if X[i][j] == X[i+1][j] and X[i][j] != 0:
                count += 1
    return count