1

I get as an input N*M matrix (tuple of tuples), values from 1 to 9.

What is the best way to hash this structure, so I can get the place (x,y) of every 8 value? (8 for example, can be 5 or 7...)

3 Answers 3

3

Since you want to find the location of 5s and 7s and 8s, it may be more efficient to store all the locations in a dict with one pass through the matrix, instead of one pass for the 5s, one pass for the 7s, etc...

loc = {}    
for x in range(N):
    for y in range(M):
        loc.setdefault(matrix[x][y], []).append((x,y))
Sign up to request clarification or add additional context in comments.

2 Comments

but I would like to access with O(1), since my program searches all the time for values in changing matrix
Dict access is O(1). See the TimeComplexity wiki.
1

"Hash" is the wrong word for this. You just want to search a 2D array for a particular value. Maybe something like this...

height = len(data)
width = len(data[0])
eights = [(x, y) for y in range(height) for x in range(width) if data[x][y] == 8]

1 Comment

but I would like to access with O(1), since my program searches all the time for values in changing matrix
0
[(x,y) for x in range(N) for y in range(M) if matrix[x][y] == 8]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.