gizgok
gizgok

Reputation: 7649

Reading adjacent elements in graph in python

I'm representing a graph in python in a list in this manner:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

What I want now is all the adjacent elements of a particular node?

For e.g

1 -> 2, 4, 5
5 -> 1, 2, 3, 4, 6, 7, 8, 9

I understand the way to do would be combinations of i-1,i+1, j-1, j+1 with i and j as rows and columns. But seems natural to suit a C solution where you put boundary constraints in the for loops.

Is there a pythonic way to do it without checking boundary constraints for all the 8 possible choices.

There is no ordering that I need. The matrix here can be any m x n.

Upvotes: 1

Views: 301

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

You can use itertools.product:

>>> from itertools import product
>>> lis = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> points = list(product([0, 1, -1], repeat=2))[1:]
def get_adj_items(i, j, m, n, lis):
    return [lis[i+x][j+y] for x, y in points 
                                         if 0 <= x+i < m and 0 <= y+j < n]
... 
>>> get_adj_items(0, 0, 3, 3, lis)
[2, 4, 5]
>>> get_adj_items(1, 1, 3, 3, lis) 
[6, 4, 8, 9, 7, 2, 3, 1]

2X4 matrix:

>>> lis = [[1, 2, 3 ,4], [5, 6 ,7 ,8]]
>>> get_adj_items(1, 1, 2, 4, lis)     #items adjacent  to 6
[7, 5, 2, 3, 1]

Upvotes: 1

Related Questions