Created
May 19, 2018 21:14
-
-
Save scriptpapi/935f008cd1e64f8f15a9bea1581cd141 to your computer and use it in GitHub Desktop.
a simple python weighted graph data structure implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Simple graph implementation (not tested) | |
class Node: | |
def __init__(self, newData): | |
self.data = newData | |
self.adjacencyList = {} | |
def addAdjacent(self, adj, weight): | |
self.adjacencyList[adj] = weight | |
def getAdjacents(self): | |
return self.adjacencyList.keys() | |
def setData(self, newData): | |
self.data = newData | |
def getData(self): | |
return self.data | |
def getWeight(self, adj): | |
return self.adjacencyList[adj] | |
def __str__(self): | |
return str(self.data) + ": " + str([x.getData for x in self.adjacencyList]) | |
class Graph: | |
def __init__(self): | |
self.nodeList = {} | |
self.size = 0 | |
def add(self, key): | |
self.nodeList = Node(key) | |
self.size += 1 | |
def addEdge(self, i_key, f_key, weight): | |
if i_key not in self.nodeList: | |
self.add(i_key) | |
if f_key not in self.nodeList: | |
self.add(f_key) | |
self.nodeList[i_key].addAdjacent(self.nodeList[f_key], weight) | |
def setEdgeWeight(self, i_key, f_key, weight): | |
if i_key not in self.nodeList: | |
raise ValueError("Edge doesn't exist") | |
if f_key not in self.nodeList: | |
raise ValueError("Edge doesn't exist") | |
self.nodeList[i_key].addAdjacent(self.nodeList[f_key], weight) | |
def find(self, key): | |
if key in self.nodeList: | |
return True | |
else: | |
return False | |
def remove(self, key): | |
if key in self.nodeList: | |
del self.nodeList[key] | |
else: | |
return False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment