Created
March 5, 2018 17:52
-
-
Save loisgh/827c9844b66f8908e2279e184548fb01 to your computer and use it in GitHub Desktop.
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
class Node: | |
# Constructor to initialize the node object | |
def __init__(self, data, neighbors=[]): | |
self.data = data | |
self.neighbors = [] | |
class Graph: | |
def __init__(self): | |
self.head = None | |
def create_graph(self, adj_dict_list, nodes): | |
graphs = [] | |
keys = sorted(nodes.keys()) | |
for adj_dict in adj_dict_list: | |
graph = Graph() | |
keys_from_adj_dict = sorted(adj_dict.keys()) | |
for key in keys_from_adj_dict: | |
if key in adj_dict: | |
the_neighbors = adj_dict[key] | |
for neighbor in the_neighbors: | |
nodes[key].neighbors.append(nodes[neighbor]) | |
graph.head = nodes[keys_from_adj_dict[0]] | |
graphs.append(graph) | |
return graphs | |
def create_nodes(self, keys): | |
node_dict = {} | |
for key in keys: | |
new_node = Node(key) | |
node_dict[key] = new_node | |
return node_dict | |
def print_graph(self, current, visited={}): | |
while current and current.data not in visited: | |
if current.neighbors: | |
print(current.data) | |
visited[current.data] = 0 | |
print self.print_neighbors(current) | |
for neighbor in current.neighbors: | |
current = neighbor | |
return self.print_graph(current, visited) | |
def print_neighbors(self, current): | |
n_string = " " | |
for neighbor in current.neighbors: | |
n_string += neighbor.data | |
n_string += " " | |
return n_string | |
def create_adj_dict(vert_list): | |
adj_dict = {} | |
list_of_nodes = {} | |
list_of_adj = [] | |
last_vertex = None | |
for vertex in vert_list: | |
if last_vertex != None and last_vertex != vertex[0]: | |
list_of_adj.append(adj_dict) | |
adj_dict = {} | |
list_of_nodes[vertex[0]] = 0 | |
list_of_nodes[vertex[1]] = 0 | |
if vertex[0] in adj_dict: | |
adj_dict[vertex[0]].append(vertex[1]) | |
else: | |
adj_dict[vertex[0]] = [vertex[1]] | |
last_vertex = vertex[1] | |
if adj_dict: | |
list_of_adj.append(adj_dict) | |
return list_of_adj, list_of_nodes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment