Roberto Mena - 2 months ago 13

Python Question

I need ideas, this is not a homework .......

I have the following matrix, how i can obtain the coordinates of duplicates numbers,

duplicates [ [ [0,0],[1,0],[2,0],[0,1],[0,2],[1,2],[1,3],[2,2] ], [ [0,3], [0,4] , ........ ]

momentary code:

`n = [ [1,1,1,3,3],[1,2,1,1,2],[1,2,1,3,3] ]`

coordinates = [[-1,0],[0,1],[1,0],[0,-1]]

i = 0

while i < len(n):

j = 0

fila = []

while j < len(n[0]):

for coordinate in coordinates:

X = i + coordinate[0]

Y = j + coordinate[1]

if X >= 0 and X < len(n) and Y >= 0 and Y < len(n[0]):

# I tried with two for in here but its not efficient

j+=1

i+=1

Thanks

EDIT:

expected output:

Groups 1, separated 2, separated 3 and only 2

duplicates [ [ [0,0],[1,0],[2,0],[0,1],[0,2],[1,2],[1,3],[2,2] ], [ [0,3], [0,4] ], [ [1,1],[2,1] ] , [ [1,4] ], [ [2,3], [2,4] ]

Answer

Not extremely efficient, as the test array is used in a logical comparison check multiple times, but most loops are pushed to the C-level. At the same time, it demonstrates a few interesting methods you could explore if you have similar functionality to perform.

```
import scipy.ndimage as nd
import numpy as np
n = np.array([ [1,1,1,3,3],[1,2,1,1,2],[1,2,1,3,3] ], dtype=np.int)
def print_coord(val, pos, shape):
print("{}: {}".format(val[0], list(zip(*np.unravel_index(pos, dims=shape)))))
return 0
for val in np.unique(n):
labelled_array, num_features = nd.label(n == val)
nd.labeled_comprehension(n, labelled_array, [1,2,3],
lambda v, p: print_coord(v, p, shape=n.shape), float, 0, True)
```

Output:

```
1: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 2), (1, 3), (2, 0), (2, 2)]
2: [(1, 1), (2, 1)]
2: [(1, 4)]
3: [(0, 3), (0, 4)]
3: [(2, 3), (2, 4)]
```

You could of course append the results to a list, when you are not interested in keeping the label that matched that list of coordinates.