-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraph.py
53 lines (38 loc) · 1.46 KB
/
graph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import random
class Vertex(object):
def __init__(self, value):
self.value = value
self.adjacent = {}
self.neighbors = []
self.neighbors_weights = []
def __str__(self):
return self.value + ' '.join([node.value for node in self.adjacent.keys()])
def add_edge_to(self, vertex, weight=0):
self.adjacent[vertex] = weight
def increment_edge(self, vertex):
self.adjacent[vertex] = self.adjacent.get(vertex, 0) + 1
def get_adjacent_nodes(self):
return self.adjacent.keys()
# initializes probability map
def get_probability_map(self):
for (vertex, weight) in self.adjacent.items():
self.neighbors.append(vertex)
self.neighbors_weights.append(weight)
def next_word(self):
return random.choices(self.neighbors, weights=self.neighbors_weights)[0]
class Graph(object):
def __init__(self):
self.vertices = {}
def get_vertex_values(self):
return set(self.vertices.keys())
def add_vertex(self, value):
self.vertices[value] = Vertex(value)
def get_vertex(self, value):
if value not in self.vertices:
self.add_vertex(value)
return self.vertices[value]
def get_next_word(self, current_vertex):
return self.vertices[current_vertex.value].next_word()
def generate_probability_mappings(self):
for vertex in self.vertices.values():
vertex.get_probability_map()