Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Create UnweightGraph.py
Q6) Implement an unweighted data graph structure.
- Loading branch information
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
class Node: | ||
def __init__(self, n): | ||
self.name = n | ||
|
||
class Graph: | ||
vertices = {} | ||
edges = [] | ||
edge_indices = {} | ||
|
||
def add_node(self, node): | ||
if isinstance(node, Node) and node.name not in self.vertices: | ||
self.vertices[node.name] = node | ||
for row in self.edges: | ||
row.append(0) | ||
self.edges.append([0] * (len(self.edges)+1)) | ||
self.edge_indices[node.name] = len(self.edge_indices) | ||
return True | ||
else: | ||
return False | ||
|
||
def add_edge(self, x, y, weight=1): | ||
if x in self.vertices and y in self.vertices: | ||
self.edges[self.edge_indices[x]][self.edge_indices[y]] = weight | ||
self.edges[self.edge_indices[y]][self.edge_indices[x]] = weight | ||
return True | ||
else: | ||
return False | ||
|