Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Add Comment
Please, Sign In to add comment