Aswin Murugesh
Aswin Murugesh

Reputation: 11080

Best way to find the number of distinct element in a submatrix using python

Given a matrix and a range, what is the best way to find the number of distinct elements in the sub-matrix? I tried:

for i in l[a-1:c]: #a is the start row and c is the end row
            s.extend(set(i[b-1:d]))  #b is the start column and d is the end column
     print len(set(s))

E.g)

The given matrix:

1 2 3
3 2 1
5 4 6

Given:

a = 1, b= 1, c = 2, d = 3

The answer should be 3, as there are only 3 distinct elements in the sub matrix 1,1 to 2,3

Is there any other pythonic way to do this?

Upvotes: 1

Views: 608

Answers (2)

qmorgan
qmorgan

Reputation: 4894

You can do all the slicing you need without the use of a for-loop (see below). I've used the Counter module to count the number of unique items in the remaining sub-matrix.

from collections import Counter
import numpy as np

mat=[[1,2,3],[3,2,1],[5,4,6]]
mat = np.matrix(mat)

submat = mat[a-1:c,b-1:d] # extract the sub matrix desired

flattened = np.array(submat.flatten()).flatten() #flatten it for use in counter

print Counter(flattened) # prints the counts of each unique item

len_unique = len(Counter(flattened)) # the total number of unique items.

Upvotes: 1

Exthen
Exthen

Reputation: 13

from itertools import chain

set(chain.from_iterable([t[b-1:d] for t in l[a-1:c]]))

# len(...)  this should get the length

Upvotes: 1

Related Questions