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
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@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