Adjacency Matrix (Graph) in Python

Adjacency matrix is a widely used graph data structure used to store graph. Couple of days ago I had to write a Python code that reads user input from console and stores the graph in an adjacency matrix. I used List for this purpose. Here is my code:-


def graph_input():
V = int(raw_input("Enter the number of Nodes: "))
E = int(raw_input("Enter the number of Edges: "))

print "Enter Edges with weights:\n"

adj_matrix = []
# vertex numbering starts from 0
for i in range(0, V):
temp = []
for j in range(0, V):
temp.append(0)
adj_matrix.append(temp)

for i in range(0, E):
s = raw_input()
u, v, w = s.split()
u = int(u)
v = int(v)
w = int(w)
adj_matrix[v][u] = adj_matrix[u][v] = w

# print the adjacency matrix
for i in range (0, V):
print adj_matrix[i]

return adj_matrix

graph = graph_input()


Let me know if you have any other idea to represent a graph using adjacency matrix in Python.

Comments

analogit said…
sorry, I'm new to python, what would the input for edge weights look like?
Tamim Shahriar said…
2 4 10

(u = 2, v = 4, w (weight) = 10)
M. Shafique said…
I need to construct an adjacency matrix (634*634) from an incidence matrix (634*100).

I tried to find a python code for that but found nothing on that.

Any help in this regards will be highly appreciated.
Following Magnus Lie Hetland in "Python Algorithms"pp. 87, one can make up a random matrix like these:

## Creation of a random adjacency matrix
from random import randrange
n = 10
G = [[randrange(2) for i in range(n)] for i in range(n)]

##Those lines create a 10 X 10 random adjacency matrix filled with zeros and '1's.
## Hope it is worth knowing
I have an interaction list with me how to convert it into adjacency matrix
Unknown said…
This comment has been removed by the author.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code