Ram Alsafadi
Ram Alsafadi

Reputation: 13

Dealing with 2D array element indexes in python

I have a 2D boolean array and I’m trying to set the elements surrounded by true to the value “true”:

For example:

[[T,T,T,F],[T,F,T,T],[T,T,T,T]]

Would become:

[[T,T,T,F],[T,T,T,T],[T,T,T,T]]

The false in the second raw and the second column would be true.

So I think I'm gonna need the index for every element to compare this seems easy in other languages like java but I need to do it in python.

I tried to do this in a for loop as :

For i in Range(len(s)) :
    If s[i+1] 
    If s[i-1] 

And of course, tried it with two for loops. Any ideas?

Upvotes: 0

Views: 43

Answers (2)

alani
alani

Reputation: 13049

import numpy as np

T = True
F = False

a = np.array([[T,T,T,F],[T,F,T,T],[T,T,T,T]])

a[1:-1, 1:-1] |= (a[:-2,  :-2] & a[:-2, 1:-1] & a[:-2,  2:] &
                  a[1:-1, :-2]                & a[1:-1, 2:] &
                  a[2:,   :-2] & a[2:,  1:-1] & a[2:,   2:])

print(a)

gives:

[[ True  True  True False]
 [ True  True  True  True]
 [ True  True  True  True]]

Or if by "surrounded by" you just mean the four elements that are directly adjacent (not diagonally adjacent), then the expression becomes:

a[1:-1, 1:-1] |= (               a[ :-2, 1:-1]               &              
                  a[1:-1, :-2]                 & a[1:-1, 2:] &
                                 a[2:,   1:-1]              )

maybe better written as:

a[1:-1, 1:-1] |= (a[:-2, 1:-1] & a[1:-1, :-2] & a[1:-1, 2:] & a[2:, 1:-1])

And the result for this particular example array is the same as before.

Upvotes: 1

pslessard
pslessard

Reputation: 71

You do it just like you would in Java or any other language. Here's one possible implementation that doesn't use numpy and might be more beginner-friendly. You didn't specify if it includes the corners, so this only factors in the ones that are directly adjacent.

for row_index in range(len(s)):                 # Loops through each row in the array
    for col_index in range(len(s[row_index])):  # Loops through each column in the row
        # Make sure you check for out of bounds
        if ((row_index > 0 and s[row_index - 1][col_index]) and
            (row_index < len(s)-1 and s[row_index + 1][col_index]) and
            (col_index > 0 and s[row_index][col_index - 1]) and
            (col_index < len(s[0])-1 and s[row_index][col_index + 1])):
            s[row_index][col_index] = True

Upvotes: 1

Related Questions