Skip to content

Commit 475600c

Browse files
authored
Create Graphs (basic)
1 parent ad4da1f commit 475600c

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Graphs (basic)

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
#Script file
2+
from random import randrange
3+
from graph import Graph
4+
from vertex import Vertex
5+
6+
def print_graph(graph):
7+
for vertex in graph.graph_dict:
8+
print("")
9+
print(vertex + " connected to")
10+
vertex_neighbors = graph.graph_dict[vertex].edges
11+
if len(vertex_neighbors) == 0:
12+
print("No edges!")
13+
for adjacent_vertex in vertex_neighbors:
14+
print("=> " + adjacent_vertex)
15+
16+
17+
def build_graph(directed):
18+
g = Graph(directed)
19+
vertices = []
20+
for val in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:
21+
vertex = Vertex(val)
22+
vertices.append(vertex)
23+
g.add_vertex(vertex)
24+
25+
for v in range(len(vertices)):
26+
v_idx = randrange(0, len(vertices) - 1)
27+
v1 = vertices[v_idx]
28+
v_idx = randrange(0, len(vertices) - 1)
29+
v2 = vertices[v_idx]
30+
g.add_edge(v1, v2, randrange(1, 10))
31+
32+
print_graph(g)
33+
34+
build_graph(False)
35+
36+
#Graph file
37+
class Graph:
38+
def __init__(self, directed = False):
39+
self.graph_dict = {}
40+
self.directed = directed
41+
42+
def add_vertex(self, vertex):
43+
self.graph_dict[vertex.value] = vertex
44+
45+
def add_edge(self, from_vertex, to_vertex, weight = 0):
46+
self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
47+
if not self.directed:
48+
self.graph_dict[to_vertex.value].add_edge(from_vertex.value, weight)
49+
50+
def find_path(self, start_vertex, end_vertex):
51+
start = [start_vertex]
52+
seen = {}
53+
while len(start) > 0:
54+
current_vertex = start.pop(0)
55+
seen[current_vertex] = True
56+
print("Visiting " + current_vertex)
57+
if current_vertex == end_vertex:
58+
return True
59+
else:
60+
vertices_to_visit = set(self.graph_dict[current_vertex].edges.keys())
61+
start += [vertex for vertex in vertices_to_visit if vertex not in seen]
62+
return False
63+
64+
#Vertex file
65+
class Vertex:
66+
def __init__(self, value):
67+
self.value = value
68+
self.edges = {}
69+
70+
def add_edge(self, vertex, weight = 0):
71+
self.edges[vertex] = weight
72+
73+
def get_edges(self):
74+
return list(self.edges.keys())
75+

0 commit comments

Comments
 (0)