Skip to content

Instantly share code, notes, and snippets.

@anirudhjayaraman
Created July 28, 2016 07:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save anirudhjayaraman/1f74eb656c3dd85ff440fb9f9267f70a to your computer and use it in GitHub Desktop.
Save anirudhjayaraman/1f74eb656c3dd85ff440fb9f9267f70a to your computer and use it in GitHub Desktop.
Python Implementation of Undirected Graphs (Adjacency List and Adjacency Matrix)
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{}\n",
"\n",
"{}\n",
"\n",
"\n",
"[\"A:['B', 'C', 'E']\", \"C:['A', 'B', 'D', 'E']\", \"B:['A', 'C', 'D']\", \"E:['A', 'C']\", \"D:['B', 'C']\"]\n",
"\n",
"[[ 0. 1. 1. 0. 1.]\n",
" [ 1. 0. 1. 1. 0.]\n",
" [ 1. 1. 0. 1. 1.]\n",
" [ 0. 1. 1. 0. 0.]\n",
" [ 1. 0. 1. 0. 0.]]\n"
]
}
],
"source": [
"class Vertex:\n",
" def __init__(self, vertex):\n",
" self.name = vertex\n",
" self.neighbors = []\n",
" \n",
" def add_neighbor(self, neighbor):\n",
" if isinstance(neighbor, Vertex):\n",
" if neighbor.name not in self.neighbors:\n",
" self.neighbors.append(neighbor.name)\n",
" neighbor.neighbors.append(self.name)\n",
" self.neighbors = sorted(self.neighbors)\n",
" neighbor.neighbors = sorted(neighbor.neighbors)\n",
" else:\n",
" return False\n",
" \n",
" def add_neighbors(self, neighbors):\n",
" for neighbor in neighbors:\n",
" if isinstance(neighbor, Vertex):\n",
" if neighbor.name not in self.neighbors:\n",
" self.neighbors.append(neighbor.name)\n",
" neighbor.neighbors.append(self.name)\n",
" self.neighbors = sorted(self.neighbors)\n",
" neighbor.neighbors = sorted(neighbor.neighbors)\n",
" else:\n",
" return False\n",
" \n",
" def __repr__(self):\n",
" return str(self.neighbors)\n",
"\n",
"\n",
"class Graph:\n",
" def __init__(self):\n",
" self.vertices = {}\n",
" \n",
" def add_vertex(self, vertex):\n",
" if isinstance(vertex, Vertex):\n",
" self.vertices[vertex.name] = vertex.neighbors\n",
"\n",
" \n",
" def add_vertices(self, vertices):\n",
" for vertex in vertices:\n",
" if isinstance(vertex, Vertex):\n",
" self.vertices[vertex.name] = vertex.neighbors\n",
"\n",
" \n",
" def add_edge(self, vertex_from, vertex_to):\n",
" if isinstance(vertex_from, Vertex) and isinstance(vertex_to, Vertex):\n",
" vertex_from.add_neighbor(vertex_to)\n",
" if isinstance(vertex_from, Vertex) and isinstance(vertex_to, Vertex):\n",
" self.vertices[vertex_from.name] = vertex_from.neighbors\n",
" self.vertices[vertex_to.name] = vertex_to.neighbors\n",
" \n",
" def add_edges(self, edges):\n",
" for edge in edges:\n",
" self.add_edge(edge[0],edge[1]) \n",
" \n",
" def adjacencyList(self):\n",
" if len(self.vertices) >= 1:\n",
" return [str(key) + \":\" + str(self.vertices[key]) for key in self.vertices.keys()] \n",
" else:\n",
" return dict()\n",
" \n",
" def adjacencyMatrix(self):\n",
" if len(self.vertices) >= 1:\n",
" self.vertex_names = sorted(g.vertices.keys())\n",
" self.vertex_indices = dict(zip(self.vertex_names, range(len(self.vertex_names)))) \n",
" import numpy as np\n",
" self.adjacency_matrix = np.zeros(shape=(len(self.vertices),len(self.vertices)))\n",
" for i in range(len(self.vertex_names)):\n",
" for j in range(i, len(self.vertices)):\n",
" for el in g.vertices[self.vertex_names[i]]:\n",
" j = g.vertex_indices[el]\n",
" self.adjacency_matrix[i,j] = 1\n",
" return self.adjacency_matrix\n",
" else:\n",
" return dict() \n",
" \n",
"\n",
"def graph(g):\n",
" \"\"\" Function to print a graph as adjacency list and adjacency matrix. \"\"\"\n",
" return str(g.adjacencyList()) + '\\n' + '\\n' + str(g.adjacencyMatrix())\n",
"\n",
"###################################################################################\n",
"\n",
"a = Vertex('A')\n",
"b = Vertex('B')\n",
"c = Vertex('C')\n",
"d = Vertex('D')\n",
"e = Vertex('E')\n",
"\n",
"a.add_neighbors([b,c,e]) \n",
"b.add_neighbors([a,c])\n",
"c.add_neighbors([b,d,a,e])\n",
"d.add_neighbor(c)\n",
"e.add_neighbors([a,c])\n",
" \n",
" \n",
"g = Graph()\n",
"print graph(g)\n",
"print \n",
"g.add_vertices([a,b,c,d,e])\n",
"g.add_edge(b,d)\n",
"print\n",
"print graph(g)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.11"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@AST9712
Copy link

AST9712 commented Nov 29, 2017

It gives syntax error on print graph(g). What do I do?

@itaditya
Copy link

itaditya commented Jan 4, 2018

class Vertex:
    def __init__(self, vertex):
        self.name = vertex
        self.neighbors = []
        
    def add_neighbor(self, neighbor):
        if isinstance(neighbor, Vertex):
            if neighbor.name not in self.neighbors:
                self.neighbors.append(neighbor.name)
                neighbor.neighbors.append(self.name)
                self.neighbors = sorted(self.neighbors)
                neighbor.neighbors = sorted(neighbor.neighbors)
        else:
            return False
        
    def add_neighbors(self, neighbors):
        for neighbor in neighbors:
            if isinstance(neighbor, Vertex):
                if neighbor.name not in self.neighbors:
                    self.neighbors.append(neighbor.name)
                    neighbor.neighbors.append(self.name)
                    self.neighbors = sorted(self.neighbors)
                    neighbor.neighbors = sorted(neighbor.neighbors)
            else:
                return False
        
    def __repr__(self):
        return str(self.neighbors)


class Graph:
    def __init__(self):
        self.vertices = {}
    
    def add_vertex(self, vertex):
        if isinstance(vertex, Vertex):
            self.vertices[vertex.name] = vertex.neighbors

            
    def add_vertices(self, vertices):
        for vertex in vertices:
            if isinstance(vertex, Vertex):
                self.vertices[vertex.name] = vertex.neighbors

            
    def add_edge(self, vertex_from, vertex_to):
        if isinstance(vertex_from, Vertex) and isinstance(vertex_to, Vertex):
            vertex_from.add_neighbor(vertex_to)
            if isinstance(vertex_from, Vertex) and isinstance(vertex_to, Vertex):
                self.vertices[vertex_from.name] = vertex_from.neighbors
                self.vertices[vertex_to.name] = vertex_to.neighbors
                
    def add_edges(self, edges):
        for edge in edges:
            self.add_edge(edge[0],edge[1])          
    
    def adjacencyList(self):
        if len(self.vertices) >= 1:
                return [str(key) + ":" + str(self.vertices[key]) for key in self.vertices.keys()]  
        else:
            return dict()
        
    def adjacencyMatrix(self):
        if len(self.vertices) >= 1:
            self.vertex_names = sorted(g.vertices.keys())
            self.vertex_indices = dict(zip(self.vertex_names, range(len(self.vertex_names)))) 
            import numpy as np
            self.adjacency_matrix = np.zeros(shape=(len(self.vertices),len(self.vertices)))
            for i in range(len(self.vertex_names)):
                for j in range(i, len(self.vertices)):
                    for el in g.vertices[self.vertex_names[i]]:
                        j = g.vertex_indices[el]
                        self.adjacency_matrix[i,j] = 1
            return self.adjacency_matrix
        else:
            return dict()              
                        

def graph(g):
    """ Function to print a graph as adjacency list and adjacency matrix. """
    return str(g.adjacencyList()) + '\n' + '\n' + str(g.adjacencyMatrix())

###################################################################################

a = Vertex('A')
b = Vertex('B')
c = Vertex('C')
d = Vertex('D')
e = Vertex('E')

a.add_neighbors([b,c,e]) 
b.add_neighbors([a,c])
c.add_neighbors([b,d,a,e])
d.add_neighbor(c)
e.add_neighbors([a,c])
        
        
g = Graph()
print(graph(g))
print("\n")
g.add_vertices([a,b,c,d,e])
g.add_edge(b,d)
print("\n")
print(graph(g))

@itaditya
Copy link

itaditya commented Jan 4, 2018

You must be using Python 3.x whereas the author's code is for Python 2.x. Try to run mine...

@isiddharthsingh
Copy link

`class Vertex:
def init(self,key):
self.id = key
self.connectedTo = {}

def addNeighbor(self,nbr,weight=0):
    self.connectedTo[nbr] = weight

def __str__(self):
    return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])

def getConnections(self):
    return self.connectedTo.keys()

def getId(self):
    return self.id

def getWeight(self,nbr):
    return self.connectedTo[nbr]

class Graph:
def init(self):
self.vertList = {}
self.numVertices = 0

def addVertex(self,key):
    self.numVertices = self.numVertices + 1
    newVertex = Vertex(key)
    self.vertList[key] = newVertex
    return newVertex

def getVertex(self,n):
    if n in self.vertList:
        return self.vertList[n]
    else:
        return None

def addEdge(self,f,t,cost=0):
    if f not in self.vertList:
        nv = self.addVertex(f)
    if t not in self.vertList:
        nv = self.addVertex(t)
    self.vertList[f].addNeighbor(self.vertList[t], cost)

def getVertices(self):
    return self.vertList.keys()

def __iter__(self):
    return iter(self.vertList.values())

def __contains__(self,n):
    return n in self.vertList`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment