-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphColoringDplus1.py
69 lines (60 loc) · 1.87 KB
/
graphColoringDplus1.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
def getDegree(graph):
#nodes = graph
degree = 0
for node in graph:
if degree < len(node.neighbors):
degree = len(node.neighbors)
return degree
def colorGraph(node,color,visited):
if color:
if node.color == None:
visited[node.label] = color.pop(0)
node.color = visited[node.label] # assign color
neighbors = node.neighbors # get neighbours
for neighbor in neighbors:
print neighbor.label
if not(neighbor.label in visited): # if neighbour is unique
print neighbor.label
print color
if color: # color is not empty
neighbor.color = color.pop(0)
visited[neighbor.label] = neighbor.color
else: #backtrack
return visited
return visited
def my_function(arg):
# Write the body of your function here
degree = getDegree(arg)
visited = {} # node.label : color
color = [i for i in range(0, degree+1,1)] # all colors
print color
#arg = colorGraph(arg,color,visited)
for node in graph:
print node
visited = colorGraph(node,color,visited)
#copy Colors
for node in graph:
if node.label in visited:
node.color = visited[node.label]
return arg
#return 'running with %s' % arg
def print_my_function(graph):
graph = my_function(graph)
for node in graph:
print(node.label, node.color)
# Run your function through some test cases here
# Remember: debugging is half the battle!
class GraphNode:
def __init__(self, label):
self.label = label
self.neighbors = set()
self.color = None
a = GraphNode('a')
b = GraphNode('b')
c = GraphNode('c')
a.neighbors.add(b)
b.neighbors.add(a)
b.neighbors.add(c)
c.neighbors.add(b)
graph = [a, b, c]
print_my_function(graph)