Guest User

Untitled

a guest
May 24th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. # Simple graph implementation (not tested)
  2.  
  3.  
  4. class Node:
  5. def __init__(self, newData):
  6. self.data = newData
  7. self.adjacencyList = {}
  8.  
  9. def addAdjacent(self, adj, weight):
  10. self.adjacencyList[adj] = weight
  11.  
  12. def getAdjacents(self):
  13. return self.adjacencyList.keys()
  14.  
  15. def setData(self, newData):
  16. self.data = newData
  17.  
  18. def getData(self):
  19. return self.data
  20.  
  21. def getWeight(self, adj):
  22. return self.adjacencyList[adj]
  23.  
  24. def __str__(self):
  25. return str(self.data) + ": " + str([x.getData for x in self.adjacencyList])
  26.  
  27.  
  28. class Graph:
  29. def __init__(self):
  30. self.nodeList = {}
  31. self.size = 0
  32.  
  33. def add(self, key):
  34. self.nodeList = Node(key)
  35. self.size += 1
  36.  
  37. def addEdge(self, i_key, f_key, weight):
  38. if i_key not in self.nodeList:
  39. self.add(i_key)
  40. if f_key not in self.nodeList:
  41. self.add(f_key)
  42. self.nodeList[i_key].addAdjacent(self.nodeList[f_key], weight)
  43.  
  44. def setEdgeWeight(self, i_key, f_key, weight):
  45. if i_key not in self.nodeList:
  46. raise ValueError("Edge doesn't exist")
  47. if f_key not in self.nodeList:
  48. raise ValueError("Edge doesn't exist")
  49. self.nodeList[i_key].addAdjacent(self.nodeList[f_key], weight)
  50.  
  51. def find(self, key):
  52. if key in self.nodeList:
  53. return True
  54. else:
  55. return False
  56.  
  57. def remove(self, key):
  58. if key in self.nodeList:
  59. del self.nodeList[key]
  60. else:
  61. return False
Add Comment
Please, Sign In to add comment