-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraph.py
109 lines (88 loc) · 2.39 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
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
from utils import *
class Graph(object):
"""
Un graphe oriente -> G = (X, U)
- X, un ensemble de sommets
- U, arcs de G, une famille de X x X
"""
def __init__(self, som=[], arcs=[]):
self.X = som
self.U = arcs
def __eq__(self, other):
return self.X == other.X and self.U == other.U
def __ne__(self, other):
return self.X != other.X or self.U != other.U
def __contains__(self, elt):
return elt in self.U
def not__contains__(self, elt):
return elt not in self.U
def printg(self):
print "X", self.X
print "U", self.U
# Totally ineffective method
# But I don't want to be smart
def matrix(self):
ss = " |"
for s in self.X:
ss+=str(s)+"|"
for e1 in self.X:
ss+="\n"+str(e1)+"|"
for e2 in self.X:
if (e2, e1) in self.U:
ss+="1|"
else:
ss+=" |"
print ss
def succ(self, som):
res = []
for arc in self.U:
if arc[0] == som:
res.append(arc[1])
return res
def pred(self, som):
res = []
for arc in self.U:
if arc[1] == som:
res.append(arc[0])
return res
def adja(self, s):
adj = []
for arc in self.U:
if arc[0] == s:
adj.append(arc[1])
elif arc[1] == s:
adj.append(arc[0])
return adj
def maxAdja(self):
adj = 0
for i in self.X:
adj = max(adj, len(self.adja(i)))
return adj
class ValuedGraph(Graph):
"""
Graphe value
X -> sommets
U -> arcs
V -> value {(x, y): v}
"""
def __init__(self, som, arc, val):
super(ValuedGraph, self).__init__(som, arc)
self.V = val
def getValue(self, i, j):
if (i,j) in self.V.keys():
return self.V[(i,j)]
elif (j,i) in self.V.keys():
return self.V[(j,i)]
else:
raise UnknownEdgeException("Can't fing the edge ", (i,j), " in ", self.V)
def printg(self):
print self.X
print self.V
if __name__ == "__main__":
som = [1,2,3,4,5]
arcs = [(1,3), (2,1), (2,3), (2,2), (4,3), (5,3) ,(5,4)]
g = Graph(som, arcs)
g.printg()
print g.pred(3)
print g.succ(2)
g.matrix()