Repository navigation
Expand file tree
/
Copy pathbasicgraph.py
More file actions
191 lines (154 loc) · 5.18 KB
/
Copy pathbasicgraph.py
File metadata and controls
191 lines (154 loc) · 5.18 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 17 20:06:10 2018
@author: Kyle_hall
"""
# Class to represent nodes (vertices) of a graph
#
class Node(object):
# name must be a string
def __init__(self, name, dist = 0, parent = None):
self.name = name
self.status = 'unseen'
self.dist = 0
self.parent = None
def getName(self):
return self.name
def getStatus(self):
return self.status
# should be one of 'unseen', 'seen', 'processed'
def setStatus(self, status):
self.status = status
def __repr__(self):
return "<{}>".format(self.name)
def setDist(self,dist):
self.dist = dist
def getDist(self):
return self.dist
def setParent(self,parent):
self.parent = parent
def getParent(self):
return self.parent
# Class for representing undirected graphs, i.e. graphs in which edges
# have no direction - if there is an edge between a and b,
# you can "move" from a to b and/or from b to a
#
class Graph():
#nodes is a list of the nodes in the graph
#
# edges is a list of two-tuples (n1, n2). If there is an edge between n1 and n2, either (n1, n2)
# or (n2, n1) will be in the list of edges
#
# adjacencyLists is a dictionary with the set of nodes as the set of keys. For each node, n1,
# adjacencyLists[n1] is a list of the nodes n2 such that (n1,n2) is an edge.
# i.e. it is a list of all nodes to which n1 is connected directly by an edge.
#
def __init__(self):
self.nodes = []
self.edges = []
self.adjacencyLists = {}
def addNode(self, node):
if node in self.nodes:
raise ValueError("node is already in graph. You can't add it again.")
else:
self.nodes.append(node)
self.adjacencyLists[node] = []
# To add an edge between node1 and node2, node1 and node2 must already be in the graph
def addEdge(self, node1, node2):
if node1 == node2:
raise ValueError("edges to self are not allowed in undirected graphs")
if not((node1 in self.nodes) and (node2 in self.nodes)):
raise ValueError("at least one node of given edge is not in the graph")
if node2 in self.adjacencyLists[node1]:
raise ValueError("edge is already in graph. You can't add it again.")
self.edges.append((node1, node2))
self.adjacencyLists[node1].append(node2)
self.adjacencyLists[node2].append(node1)
def neighborsOf(self, node):
return self.adjacencyLists[node]
def getNode(self, name):
for node in self.nodes:
if node.getName() == name:
return node
return None
def hasNode(self, node):
return node in self.nodes
def hasEdge(self, node1, node2):
return node2 in self.adjacencyLists[node1]
def __repr__(self):
result = "[Graph with:\n Nodes:"
for node in self.nodes:
result = result + " " + str(node)
result = result + "\n Edges: "
result = result + ', '.join([(edge[0].getName() + '-' + edge[1].getName()) for edge in self.edges]) + ']'
return result
def genGraph():
n1 = Node("NYC")
n2 = Node("Miami")
g = Graph()
print(g)
g.addNode(n1)
g.addNode(n2)
print(g)
g.addEdge(n1, n2)
print(g)
return g
def genCompleteGraph(n):
nodes = []
g = Graph()
for i in range(n):
g.addNode(Node(str(i)))
nodes = g.nodes
for n1 in nodes:
for n2 in nodes:
if (n1 != n2) and (not g.hasEdge(n1, n2)):
g.addEdge(n1,n2)
return g
import random
# return a new list with the same elements as input L but randomly rearranged
def mixup(L):
newL = L[:]
length = len(L)
for i in range(length):
newIndex = random.randint(i,length-1)
newL[newIndex], newL[i] = newL[i], newL[newIndex]
return(newL)
def genRandomGraph(numNodes, numEdges):
nodes = []
edges = []
g = Graph()
for i in range(numNodes):
g.addNode(Node(str(i)))
allPairs = []
for i in range(numNodes):
for j in range(i+1, numNodes):
allPairs.append((str(i),str(j)))
allPairs = mixup(allPairs)
edgesAdded = 0
while edgesAdded < min(numEdges, len(allPairs)):
g.addEdge(g.getNode(allPairs[edgesAdded][0]), g.getNode(allPairs[edgesAdded][1]))
edgesAdded = edgesAdded + 1
return g
# graph used for bfs demo in class 4/9/18
#
def genDemoGraph():
nodes = [Node("A"), Node("B"), Node("C"), Node("D"), Node("E"), Node("F"), Node("G"), Node("H")]
# used to save typing :)
edgeIndexTuples = [(0,1), # A-B
(0,2), # A-C
(0,4), # A-E
(0,7), # A-H
(1,2), # B-C
(1,3), # B-D
(1,5), # B-F
(2,5), # C-F
(4,6), # E-G
(6,7) # G-H
]
g = Graph()
for n in nodes:
g.addNode(n)
for e in edgeIndexTuples:
g.addEdge(nodes[e[0]], nodes[e[1]])
return g